webpack.config.js 12.1 KB
Newer Older
1 2
'use strict';

3
var crypto = require('crypto');
P
Phil Hughes 已提交
4
var fs = require('fs');
5
var path = require('path');
6
var glob = require('glob');
7
var webpack = require('webpack');
8
var StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;
9
var CopyWebpackPlugin = require('copy-webpack-plugin');
M
Mike Greiling 已提交
10
var CompressionPlugin = require('compression-webpack-plugin');
11
var NameAllModulesPlugin = require('name-all-modules-plugin');
12
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
13
var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
14

15
var ROOT_PATH = path.resolve(__dirname, '..');
16
var IS_PRODUCTION = process.env.NODE_ENV === 'production';
17
var IS_DEV_SERVER = process.argv.join(' ').indexOf('webpack-dev-server') !== -1;
18
var DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
19
var DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808;
20
var DEV_SERVER_LIVERELOAD = process.env.DEV_SERVER_LIVERELOAD !== 'false';
21
var WEBPACK_REPORT = process.env.WEBPACK_REPORT;
M
Mike Greiling 已提交
22
var NO_COMPRESSION = process.env.NO_COMPRESSION;
23

24 25 26 27 28 29 30 31 32
// generate automatic entry points
var autoEntries = {};
var pageEntries = glob.sync('pages/**/index.js', { cwd: path.join(ROOT_PATH, 'app/assets/javascripts') });

pageEntries.forEach(( path ) => {
  let chunkName = path.replace(/\/index\.js$/, '').replace(/\//g, '.');
  autoEntries[chunkName] = './' + path;
});

33
var config = {
34 35 36 37
  // because sqljs requires fs.
  node: {
    fs: "empty"
  },
38
  context: path.join(ROOT_PATH, 'app/assets/javascripts'),
39
  entry: {
40
    account:              './profile/account/index.js',
41
    balsamiq_viewer:      './blob/balsamiq_viewer.js',
42 43
    blob:                 './blob_edit/blob_bundle.js',
    boards:               './boards/boards_bundle.js',
44
    common:               './commons/index.js',
45
    common_vue:           './vue_shared/vue_resource_interceptor.js',
46
    cycle_analytics:      './cycle_analytics/cycle_analytics_bundle.js',
F
Filipa Lacerda 已提交
47
    commit_pipelines:     './commit/pipelines/pipelines_bundle.js',
48
    deploy_keys:          './deploy_keys/index.js',
C
Clement Ho 已提交
49
    docs:                 './docs/docs_bundle.js',
50 51
    diff_notes:           './diff_notes/diff_notes_bundle.js',
    environments:         './environments/environments_bundle.js',
F
Filipa Lacerda 已提交
52
    environments_folder:  './environments/folder/environments_folder_bundle.js',
53
    filtered_search:      './filtered_search/filtered_search_bundle.js',
54
    graphs:               './graphs/graphs_bundle.js',
55 56
    graphs_charts:        './graphs/graphs_charts.js',
    graphs_show:          './graphs/graphs_show.js',
57
    help:                 './help/help.js',
T
Tim Zallmann 已提交
58
    how_to_merge:         './how_to_merge.js',
59
    issue_show:           './issue_show/index.js',
K
kushalpandya 已提交
60
    integrations:         './integrations',
61
    job_details:          './jobs/job_details_bundle.js',
P
Phil Hughes 已提交
62
    locale:               './locale/index.js',
63
    main:                 './main.js',
64
    merge_conflicts:      './merge_conflicts/merge_conflicts_bundle.js',
65
    monitoring:           './monitoring/monitoring_bundle.js',
66
    network:              './network/network_bundle.js',
P
Phil Hughes 已提交
67
    notebook_viewer:      './blob/notebook_viewer.js',
68
    notes:                './notes/index.js',
S
Sam Rose 已提交
69
    pdf_viewer:           './blob/pdf_viewer.js',
70
    pipelines:            './pipelines/pipelines_bundle.js',
T
Tim Zallmann 已提交
71
    pipelines_charts:     './pipelines/pipelines_charts.js',
72 73
    pipelines_details:    './pipelines/pipeline_details_bundle.js',
    pipelines_times:      './pipelines/pipelines_times.js',
74
    profile:              './profile/profile_bundle.js',
75
    project_import_gl:    './projects/project_import_gitlab_project.js',
K
kushalpandya 已提交
76
    prometheus_metrics:   './prometheus_metrics',
77
    protected_branches:   './protected_branches',
78
    protected_tags:       './protected_tags',
79
    registry_list:        './registry/index.js',
80
    ide:                 './ide/index.js',
81
    sidebar:              './sidebar/sidebar_bundle.js',
82 83
    schedule_form:        './pipeline_schedules/pipeline_schedule_form_bundle.js',
    schedules_index:      './pipeline_schedules/pipeline_schedules_index_bundle.js',
84
    snippet:              './snippet/snippet_bundle.js',
85
    sketch_viewer:        './blob/sketch_viewer.js',
P
Phil Hughes 已提交
86
    stl_viewer:           './blob/stl_viewer.js',
87
    terminal:             './terminal/terminal_bundle.js',
M
Mike Greiling 已提交
88
    u2f:                  ['vendor/u2f'],
89
    ui_development_kit:   './ui_development_kit.js',
90
    raven:                './raven/index.js',
F
Fatih Acet 已提交
91
    vue_merge_request_widget: './vue_merge_request_widget/index.js',
92
    test:                 './test.js',
93
    two_factor_auth:      './two_factor_auth.js',
94
    users:                './users/index.js',
95
    webpack_runtime:      './webpack.js',
96 97 98 99 100
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
101 102
    filename: IS_PRODUCTION ? '[name].[chunkhash].bundle.js' : '[name].bundle.js',
    chunkFilename: IS_PRODUCTION ? '[name].[chunkhash].chunk.js' : '[name].chunk.js',
103 104
  },

M
Mike Greiling 已提交
105
  module: {
M
Mike Greiling 已提交
106
    rules: [
M
Mike Greiling 已提交
107
      {
108
        test: /\.js$/,
109
        exclude: /(node_modules|vendor\/assets)/,
M
Mike Greiling 已提交
110
        loader: 'babel-loader',
F
Filipa Lacerda 已提交
111
      },
112 113
      {
        test: /\.vue$/,
M
Mike Greiling 已提交
114
        loader: 'vue-loader',
115
      },
F
Filipa Lacerda 已提交
116 117
      {
        test: /\.svg$/,
M
Mike Greiling 已提交
118 119
        loader: 'raw-loader',
      },
S
Sam Rose 已提交
120
      {
121
        test: /\.(gif|png)$/,
S
Sam Rose 已提交
122
        loader: 'url-loader',
123
        options: { limit: 2048 },
S
Sam Rose 已提交
124
      },
P
Phil Hughes 已提交
125 126
      {
        test: /\_worker\.js$/,
P
Phil Hughes 已提交
127
        use: [
P
Phil Hughes 已提交
128
          {
T
Tim Zallmann 已提交
129
            loader: 'worker-loader',
P
Phil Hughes 已提交
130
            options: {
T
Tim Zallmann 已提交
131 132 133
              inline: true
            }
          },
P
Phil Hughes 已提交
134 135
          { loader: 'babel-loader' },
        ],
P
Phil Hughes 已提交
136
      },
M
Mike Greiling 已提交
137
      {
138
        test: /\.(worker(\.min)?\.js|pdf|bmpr)$/,
S
Sam Rose 已提交
139 140
        exclude: /node_modules/,
        loader: 'file-loader',
141 142 143
        options: {
          name: '[name].[hash].[ext]',
        }
S
Sam Rose 已提交
144
      },
145 146 147 148 149 150 151 152 153 154
      {
        test: /monaco-editor\/\w+\/vs\/loader\.js$/,
        use: [
          { loader: 'exports-loader', options: 'l.global' },
          { loader: 'imports-loader', options: 'l=>{},this=>l,AMDLoader=>this,module=>undefined' },
        ],
      }
    ],

    noParse: [/monaco-editor\/\w+\/vs\//],
155
    strictExportPresence: true,
M
Mike Greiling 已提交
156 157
  },

158 159 160
  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
161 162 163 164 165 166 167 168 169 170 171 172
    new StatsWriterPlugin({
      filename: 'manifest.json',
      transform: function(data, opts) {
        var stats = opts.compiler.getStats().toJson({
          chunkModules: false,
          source: false,
          chunks: false,
          modules: false,
          assets: true
        });
        return JSON.stringify(stats, null, 2);
      }
P
Phil Hughes 已提交
173
    }),
M
Mike Greiling 已提交
174 175

    // prevent pikaday from including moment.js
P
Phil Hughes 已提交
176
    new webpack.IgnorePlugin(/moment/, /pikaday/),
M
Mike Greiling 已提交
177

178 179 180 181 182 183
    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

184
    // assign deterministic module ids
185
    new webpack.NamedModulesPlugin(),
186
    new NameAllModulesPlugin(),
187

188 189 190 191 192
    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
193 194 195 196 197 198 199 200 201 202

      const moduleNames = [];

      function collectModuleNames(m) {
        // handle ConcatenatedModule which does not have resource nor context set
        if (m.modules) {
          m.modules.forEach(collectModuleNames);
          return;
        }

203
        const pagesBase = path.join(ROOT_PATH, 'app/assets/javascripts/pages');
204

205
        if (m.resource.indexOf(pagesBase) === 0) {
206
          moduleNames.push(path.relative(pagesBase, m.resource)
207
            .replace(/\/index\.[a-z]+$/, '')
208 209 210
            .replace(/\//g, '__'));
        } else {
          moduleNames.push(path.relative(m.context, m.resource));
211
        }
212 213 214 215 216 217 218 219 220
      }

      chunk.forEachModule(collectModuleNames);

      const hash = crypto.createHash('sha256')
        .update(moduleNames.join('_'))
        .digest('hex');

      return `${moduleNames[0]}-${hash.substr(0, 6)}`;
221 222
    }),

223 224 225 226 227 228 229
    // create cacheable common library bundle for all vue chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_vue',
      chunks: [
        'boards',
        'commit_pipelines',
        'cycle_analytics',
P
Phil Hughes 已提交
230
        'deploy_keys',
231 232 233
        'diff_notes',
        'environments',
        'environments_folder',
234
        'filtered_search',
A
Alfredo Sumaran 已提交
235
        'groups',
236
        'issue_show',
237
        'job_details',
238
        'merge_conflicts',
239
        'monitoring',
P
Phil Hughes 已提交
240
        'notebook_viewer',
241
        'notes',
S
Sam Rose 已提交
242
        'pdf_viewer',
243
        'pipelines',
244
        'pipelines_details',
245
        'registry_list',
246
        'ide',
247 248 249
        'schedule_form',
        'schedules_index',
        'sidebar',
250
        'vue_merge_request_widget',
251
      ],
252 253 254
      minChunks: function(module, count) {
        return module.resource && (/vue_shared/).test(module.resource);
      },
255 256
    }),

257 258 259
    // create cacheable common library bundle for all d3 chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_d3',
260 261
      chunks: [
        'graphs',
262
        'graphs_show',
263
        'monitoring',
264
        'users',
265
      ],
266 267 268
      minChunks: function (module, count) {
        return module.resource && /d3-/.test(module.resource);
      },
269 270
    }),

271
    // create cacheable common library bundles
272
    new webpack.optimize.CommonsChunkPlugin({
273
      names: ['main', 'common', 'webpack_runtime'],
274
    }),
275

M
Mike Greiling 已提交
276 277 278
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),

279
    // copy pre-compiled vendor libraries verbatim
280 281
    new CopyWebpackPlugin([
      {
282 283 284
        from: path.join(ROOT_PATH, `node_modules/monaco-editor/${IS_PRODUCTION ? 'min' : 'dev'}/vs`),
        to: 'monaco-editor/vs',
        transform: function(content, path) {
285
          if (/\.js$/.test(path) && !/worker/i.test(path) && !/typescript/i.test(path)) {
286 287 288
            return (
              '(function(){\n' +
              'var define = this.define, require = this.require;\n' +
289
              'window.define = define; window.require = require;\n' +
290 291 292 293 294 295
              content +
              '\n}.call(window.__monaco_context__ || (window.__monaco_context__ = {})));'
            );
          }
          return content;
        }
296 297
      }
    ]),
M
Mike Greiling 已提交
298 299 300
  ],

  resolve: {
301
    extensions: ['.js'],
302
    alias: {
303
      '~':              path.join(ROOT_PATH, 'app/assets/javascripts'),
304
      'emojis':         path.join(ROOT_PATH, 'fixtures/emojis'),
305
      'empty_states':   path.join(ROOT_PATH, 'app/views/shared/empty_states'),
306
      'icons':          path.join(ROOT_PATH, 'app/views/shared/icons'),
307
      'images':         path.join(ROOT_PATH, 'app/assets/images'),
308
      'vendor':         path.join(ROOT_PATH, 'vendor/assets/javascripts'),
309
      'vue$':           'vue/dist/vue.esm.js',
310
    }
M
Mike Greiling 已提交
311
  }
312 313
}

314 315
config.entry = Object.assign({}, autoEntries, config.entry);

316
if (IS_PRODUCTION) {
M
Mike Greiling 已提交
317
  config.devtool = 'source-map';
318
  config.plugins.push(
319
    new webpack.NoEmitOnErrorsPlugin(),
M
Mike Greiling 已提交
320 321 322 323
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
324
    new webpack.optimize.UglifyJsPlugin({
M
Mike Greiling 已提交
325
      sourceMap: true
326 327 328
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
M
Mike Greiling 已提交
329
    })
330
  );
M
Mike Greiling 已提交
331

332
  // compression can require a lot of compute time and is disabled in CI
M
Mike Greiling 已提交
333
  if (!NO_COMPRESSION) {
334
    config.plugins.push(new CompressionPlugin());
M
Mike Greiling 已提交
335
  }
336 337 338
}

if (IS_DEV_SERVER) {
339
  config.devtool = 'cheap-module-eval-source-map';
340
  config.devServer = {
341
    host: DEV_SERVER_HOST,
342
    port: DEV_SERVER_PORT,
343
    disableHostCheck: true,
344 345
    headers: { 'Access-Control-Allow-Origin': '*' },
    stats: 'errors-only',
S
Simon Knox 已提交
346
    hot: DEV_SERVER_LIVERELOAD,
347
    inline: DEV_SERVER_LIVERELOAD
348
  };
349 350 351 352
  config.plugins.push(
    // watch node_modules for changes if we encounter a missing module compile error
    new WatchMissingNodeModulesPlugin(path.join(ROOT_PATH, 'node_modules'))
  );
S
Simon Knox 已提交
353 354 355
  if (DEV_SERVER_LIVERELOAD) {
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }
356 357
}

358 359 360 361 362 363 364 365 366 367 368 369
if (WEBPACK_REPORT) {
  config.plugins.push(
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      generateStatsFile: true,
      openAnalyzer: false,
      reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'),
      statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'),
    })
  );
}

370
module.exports = config;