webpack.config.js 12.6 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
// generate automatic entry points
var autoEntries = {};
var pageEntries = glob.sync('pages/**/index.js', { cwd: path.join(ROOT_PATH, 'app/assets/javascripts') });

28 29
// filter out entries currently imported dynamically in dispatcher.js
var dispatcher = fs.readFileSync(path.join(ROOT_PATH, 'app/assets/javascripts/dispatcher.js')).toString();
30
var dispatcherChunks = dispatcher.match(/(?!import\(')\.\/pages\/[^']+/g);
31

32
pageEntries.forEach(( path ) => {
33
  let chunkPath = path.replace(/\/index\.js$/, '');
34
  if (!dispatcherChunks.includes('./' + chunkPath)) {
35 36 37
    let chunkName = chunkPath.replace(/\//g, '.');
    autoEntries[chunkName] = './' + path;
  }
38 39
});

40 41 42 43
// report our auto-generated bundle count
var autoEntriesCount = Object.keys(autoEntries).length;
console.log(`${autoEntriesCount} entries from '/pages' automatically added to webpack output.`);

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

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

M
Mike Greiling 已提交
107
  module: {
M
Mike Greiling 已提交
108
    rules: [
M
Mike Greiling 已提交
109
      {
110
        test: /\.js$/,
111
        exclude: /(node_modules|vendor\/assets)/,
M
Mike Greiling 已提交
112
        loader: 'babel-loader',
F
Filipa Lacerda 已提交
113
      },
114 115
      {
        test: /\.vue$/,
M
Mike Greiling 已提交
116
        loader: 'vue-loader',
117
      },
F
Filipa Lacerda 已提交
118 119
      {
        test: /\.svg$/,
M
Mike Greiling 已提交
120 121
        loader: 'raw-loader',
      },
S
Sam Rose 已提交
122
      {
123
        test: /\.(gif|png)$/,
S
Sam Rose 已提交
124
        loader: 'url-loader',
125
        options: { limit: 2048 },
S
Sam Rose 已提交
126
      },
P
Phil Hughes 已提交
127 128
      {
        test: /\_worker\.js$/,
P
Phil Hughes 已提交
129
        use: [
P
Phil Hughes 已提交
130
          {
T
Tim Zallmann 已提交
131
            loader: 'worker-loader',
P
Phil Hughes 已提交
132
            options: {
T
Tim Zallmann 已提交
133 134 135
              inline: true
            }
          },
P
Phil Hughes 已提交
136 137
          { loader: 'babel-loader' },
        ],
P
Phil Hughes 已提交
138
      },
M
Mike Greiling 已提交
139
      {
140
        test: /\.(worker(\.min)?\.js|pdf|bmpr)$/,
S
Sam Rose 已提交
141 142
        exclude: /node_modules/,
        loader: 'file-loader',
143 144 145
        options: {
          name: '[name].[hash].[ext]',
        }
S
Sam Rose 已提交
146
      },
147 148 149 150 151
      {
        test: /katex.css$/,
        include: /node_modules\/katex\/dist/,
        use: [
          { loader: 'style-loader' },
152
          {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
            loader: 'css-loader',
            options: {
              name: '[name].[hash].[ext]'
            }
          },
        ],
      },
      {
        test: /\.(eot|ttf|woff|woff2)$/,
        include: /node_modules\/katex\/dist\/fonts/,
        loader: 'file-loader',
        options: {
          name: '[name].[hash].[ext]',
        }
      },
168 169 170 171 172 173 174 175 176 177
      {
        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\//],
178
    strictExportPresence: true,
M
Mike Greiling 已提交
179 180
  },

181 182 183
  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
184 185 186 187 188 189 190 191 192 193 194 195
    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 已提交
196
    }),
M
Mike Greiling 已提交
197 198

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

201 202 203 204 205 206
    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

207
    // assign deterministic module ids
208
    new webpack.NamedModulesPlugin(),
209
    new NameAllModulesPlugin(),
210

211 212 213 214 215
    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
216 217 218 219 220 221 222 223 224 225

      const moduleNames = [];

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

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

228
        if (m.resource.indexOf(pagesBase) === 0) {
229
          moduleNames.push(path.relative(pagesBase, m.resource)
230
            .replace(/\/index\.[a-z]+$/, '')
231 232 233
            .replace(/\//g, '__'));
        } else {
          moduleNames.push(path.relative(m.context, m.resource));
234
        }
235 236 237 238 239 240 241 242 243
      }

      chunk.forEachModule(collectModuleNames);

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

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

246 247 248 249 250 251 252
    // 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 已提交
253
        'deploy_keys',
254 255 256
        'diff_notes',
        'environments',
        'environments_folder',
257
        'filtered_search',
A
Alfredo Sumaran 已提交
258
        'groups',
259
        'issue_show',
260
        'job_details',
261
        'merge_conflicts',
262
        'monitoring',
P
Phil Hughes 已提交
263
        'notebook_viewer',
264
        'notes',
S
Sam Rose 已提交
265
        'pdf_viewer',
266
        'pipelines',
267
        'pipelines_details',
268
        'registry_list',
269
        'ide',
270 271 272
        'schedule_form',
        'schedules_index',
        'sidebar',
273
        'vue_merge_request_widget',
274
      ],
275 276 277
      minChunks: function(module, count) {
        return module.resource && (/vue_shared/).test(module.resource);
      },
278 279
    }),

280 281 282
    // create cacheable common library bundle for all d3 chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_d3',
283
      chunks: [
284
        'graphs_show',
285
        'monitoring',
286
        'users',
287
      ],
288 289 290
      minChunks: function (module, count) {
        return module.resource && /d3-/.test(module.resource);
      },
291 292
    }),

293
    // create cacheable common library bundles
294
    new webpack.optimize.CommonsChunkPlugin({
295
      names: ['main', 'common', 'webpack_runtime'],
296
    }),
297

M
Mike Greiling 已提交
298 299 300
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),

301
    // copy pre-compiled vendor libraries verbatim
302 303
    new CopyWebpackPlugin([
      {
304 305 306
        from: path.join(ROOT_PATH, `node_modules/monaco-editor/${IS_PRODUCTION ? 'min' : 'dev'}/vs`),
        to: 'monaco-editor/vs',
        transform: function(content, path) {
307
          if (/\.js$/.test(path) && !/worker/i.test(path) && !/typescript/i.test(path)) {
308 309 310
            return (
              '(function(){\n' +
              'var define = this.define, require = this.require;\n' +
311
              'window.define = define; window.require = require;\n' +
312 313 314 315 316 317
              content +
              '\n}.call(window.__monaco_context__ || (window.__monaco_context__ = {})));'
            );
          }
          return content;
        }
318 319
      }
    ]),
M
Mike Greiling 已提交
320 321 322
  ],

  resolve: {
323
    extensions: ['.js'],
324
    alias: {
325
      '~':              path.join(ROOT_PATH, 'app/assets/javascripts'),
326
      'emojis':         path.join(ROOT_PATH, 'fixtures/emojis'),
327
      'empty_states':   path.join(ROOT_PATH, 'app/views/shared/empty_states'),
328
      'icons':          path.join(ROOT_PATH, 'app/views/shared/icons'),
329
      'images':         path.join(ROOT_PATH, 'app/assets/images'),
330
      'vendor':         path.join(ROOT_PATH, 'vendor/assets/javascripts'),
331
      'vue$':           'vue/dist/vue.esm.js',
332
    }
M
Mike Greiling 已提交
333
  }
334 335
}

336 337
config.entry = Object.assign({}, autoEntries, config.entry);

338
if (IS_PRODUCTION) {
M
Mike Greiling 已提交
339
  config.devtool = 'source-map';
340
  config.plugins.push(
341
    new webpack.NoEmitOnErrorsPlugin(),
M
Mike Greiling 已提交
342 343 344 345
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
346
    new webpack.optimize.UglifyJsPlugin({
M
Mike Greiling 已提交
347
      sourceMap: true
348 349 350
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
M
Mike Greiling 已提交
351
    })
352
  );
M
Mike Greiling 已提交
353

354
  // compression can require a lot of compute time and is disabled in CI
M
Mike Greiling 已提交
355
  if (!NO_COMPRESSION) {
356
    config.plugins.push(new CompressionPlugin());
M
Mike Greiling 已提交
357
  }
358 359 360
}

if (IS_DEV_SERVER) {
361
  config.devtool = 'cheap-module-eval-source-map';
362
  config.devServer = {
363
    host: DEV_SERVER_HOST,
364
    port: DEV_SERVER_PORT,
365
    disableHostCheck: true,
366 367
    headers: { 'Access-Control-Allow-Origin': '*' },
    stats: 'errors-only',
S
Simon Knox 已提交
368
    hot: DEV_SERVER_LIVERELOAD,
369
    inline: DEV_SERVER_LIVERELOAD
370
  };
371 372 373 374
  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 已提交
375 376 377
  if (DEV_SERVER_LIVERELOAD) {
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }
378 379
}

380 381 382 383 384 385 386 387 388 389 390 391
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'),
    })
  );
}

392
module.exports = config;