webpack.config.js 11.9 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 33 34 35 36
function generateAutoEntries(path, prefix = '.') {
  const chunkPath = path.replace(/\/index\.js$/, '');
  if (!dispatcherChunks.includes(`${prefix}/${chunkPath}`)) {
    const chunkName = chunkPath.replace(/\//g, '.');
    autoEntries[chunkName] = `${prefix}/${path}`;
37
  }
38 39 40
}

pageEntries.forEach(( path ) => generateAutoEntries(path));
41

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

46
var config = {
47 48 49 50
  // because sqljs requires fs.
  node: {
    fs: "empty"
  },
51
  context: path.join(ROOT_PATH, 'app/assets/javascripts'),
52
  entry: {
53
    balsamiq_viewer:      './blob/balsamiq_viewer.js',
54
    common:               './commons/index.js',
55
    common_vue:           './vue_shared/vue_resource_interceptor.js',
56
    cycle_analytics:      './cycle_analytics/cycle_analytics_bundle.js',
F
Filipa Lacerda 已提交
57
    commit_pipelines:     './commit/pipelines/pipelines_bundle.js',
58 59
    diff_notes:           './diff_notes/diff_notes_bundle.js',
    environments:         './environments/environments_bundle.js',
F
Filipa Lacerda 已提交
60
    environments_folder:  './environments/folder/environments_folder_bundle.js',
61
    filtered_search:      './filtered_search/filtered_search_bundle.js',
62
    help:                 './help/help.js',
63
    merge_conflicts:      './merge_conflicts/merge_conflicts_bundle.js',
64
    monitoring:           './monitoring/monitoring_bundle.js',
65
    network:              './network/network_bundle.js',
P
Phil Hughes 已提交
66
    notebook_viewer:      './blob/notebook_viewer.js',
S
Sam Rose 已提交
67
    pdf_viewer:           './blob/pdf_viewer.js',
68
    pipelines:            './pipelines/pipelines_bundle.js',
69
    pipelines_details:    './pipelines/pipeline_details_bundle.js',
70
    profile:              './profile/profile_bundle.js',
71
    project_import_gl:    './projects/project_import_gitlab_project.js',
72
    protected_branches:   './protected_branches',
73
    protected_tags:       './protected_tags',
74
    registry_list:        './registry/index.js',
75
    sidebar:              './sidebar/sidebar_bundle.js',
76
    snippet:              './snippet/snippet_bundle.js',
77
    sketch_viewer:        './blob/sketch_viewer.js',
P
Phil Hughes 已提交
78
    stl_viewer:           './blob/stl_viewer.js',
79
    terminal:             './terminal/terminal_bundle.js',
80
    ui_development_kit:   './ui_development_kit.js',
F
Fatih Acet 已提交
81
    vue_merge_request_widget: './vue_merge_request_widget/index.js',
82
    two_factor_auth:      './two_factor_auth.js',
83 84 85 86 87 88 89 90 91 92


    common:               './commons/index.js',
    common_vue:           './vue_shared/vue_resource_interceptor.js',
    locale:               './locale/index.js',
    main:                 './main.js',
    ide:                  './ide/index.js',
    raven:                './raven/index.js',
    test:                 './test.js',
    u2f:                  ['vendor/u2f'],
93
    webpack_runtime:      './webpack.js',
94 95 96 97 98
  },

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

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

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

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

197 198 199 200 201 202
    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

203
    // assign deterministic module ids
204
    new webpack.NamedModulesPlugin(),
205
    new NameAllModulesPlugin(),
206

207 208 209 210 211
    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
212 213 214 215 216 217 218 219 220 221

      const moduleNames = [];

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

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

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

      chunk.forEachModule(collectModuleNames);

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

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

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

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

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

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

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

317 318
config.entry = Object.assign({}, autoEntries, config.entry);

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

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

if (IS_DEV_SERVER) {
342
  config.devtool = 'cheap-module-eval-source-map';
343
  config.devServer = {
344
    host: DEV_SERVER_HOST,
345
    port: DEV_SERVER_PORT,
346
    disableHostCheck: true,
347 348
    headers: { 'Access-Control-Allow-Origin': '*' },
    stats: 'errors-only',
S
Simon Knox 已提交
349
    hot: DEV_SERVER_LIVERELOAD,
350
    inline: DEV_SERVER_LIVERELOAD
351
  };
352 353 354 355
  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 已提交
356 357 358
  if (DEV_SERVER_LIVERELOAD) {
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
  }
359 360
}

361 362 363 364 365 366 367 368 369 370 371 372
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'),
    })
  );
}

373
module.exports = config;