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

3
var crypto = require('crypto');
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');
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;
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
function generateAutoEntries(path, prefix = '.') {
  const chunkPath = path.replace(/\/index\.js$/, '');
30 31
  const chunkName = chunkPath.replace(/\//g, '.');
  autoEntries[chunkName] = `${prefix}/${path}`;
32 33 34
}

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

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

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


    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'],
86
    webpack_runtime:      './webpack.js',
87 88 89 90 91
  },

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
92 93
    filename: IS_PRODUCTION ? '[name].[chunkhash].bundle.js' : '[name].bundle.js',
    chunkFilename: IS_PRODUCTION ? '[name].[chunkhash].chunk.js' : '[name].chunk.js',
94 95
  },

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

170 171 172
  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
173 174 175 176 177 178 179 180 181 182 183 184
    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);
      }
Phil Hughes's avatar
Phil Hughes committed
185
    }),
Mike Greiling's avatar
Mike Greiling committed
186 187

    // prevent pikaday from including moment.js
Phil Hughes's avatar
Phil Hughes committed
188
    new webpack.IgnorePlugin(/moment/, /pikaday/),
Mike Greiling's avatar
Mike Greiling committed
189

190 191 192 193 194 195
    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

196
    // assign deterministic module ids
197
    new webpack.NamedModulesPlugin(),
198
    new NameAllModulesPlugin(),
199

200 201 202 203 204
    // assign deterministic chunk ids
    new webpack.NamedChunksPlugin((chunk) => {
      if (chunk.name) {
        return chunk.name;
      }
205 206 207 208 209 210 211 212 213 214

      const moduleNames = [];

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

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

217
        if (m.resource.indexOf(pagesBase) === 0) {
218
          moduleNames.push(path.relative(pagesBase, m.resource)
219
            .replace(/\/index\.[a-z]+$/, '')
220 221 222
            .replace(/\//g, '__'));
        } else {
          moduleNames.push(path.relative(m.context, m.resource));
223
        }
224 225 226 227 228 229 230 231 232
      }

      chunk.forEachModule(collectModuleNames);

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

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

235 236 237 238 239 240 241
    // create cacheable common library bundle for all vue chunks
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common_vue',
      chunks: [
        'boards',
        'commit_pipelines',
        'cycle_analytics',
Phil Hughes's avatar
Phil Hughes committed
242
        'deploy_keys',
243 244
        'diff_notes',
        'environments',
245
        'filtered_search',
Alfredo Sumaran's avatar
Alfredo Sumaran committed
246
        'groups',
247
        'merge_conflicts',
248
        'monitoring',
249
        'notebook_viewer',
250
        'pdf_viewer',
251
        'pipelines',
252
        'pipelines_details',
253
        'registry_list',
254
        'ide',
255 256 257
        'schedule_form',
        'schedules_index',
        'sidebar',
258
        'vue_merge_request_widget',
259
      ],
260 261 262
      minChunks: function(module, count) {
        return module.resource && (/vue_shared/).test(module.resource);
      },
263 264
    }),

265
    // create cacheable common library bundles
266
    new webpack.optimize.CommonsChunkPlugin({
267
      names: ['main', 'common', 'webpack_runtime'],
268
    }),
269

270 271 272
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),

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

  resolve: {
295
    extensions: ['.js'],
296
    alias: {
297
      '~':              path.join(ROOT_PATH, 'app/assets/javascripts'),
298
      'emojis':         path.join(ROOT_PATH, 'fixtures/emojis'),
299
      'empty_states':   path.join(ROOT_PATH, 'app/views/shared/empty_states'),
300
      'icons':          path.join(ROOT_PATH, 'app/views/shared/icons'),
301
      'images':         path.join(ROOT_PATH, 'app/assets/images'),
302
      'vendor':         path.join(ROOT_PATH, 'vendor/assets/javascripts'),
303
      'vue$':           'vue/dist/vue.esm.js',
304
      'spec':           path.join(ROOT_PATH, 'spec/javascripts'),
305
    }
306
  }
307 308
}

309 310
config.entry = Object.assign({}, autoEntries, config.entry);

311
if (IS_PRODUCTION) {
312
  config.devtool = 'source-map';
313
  config.plugins.push(
314
    new webpack.NoEmitOnErrorsPlugin(),
Mike Greiling's avatar
Mike Greiling committed
315 316 317 318
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
319
    new webpack.optimize.UglifyJsPlugin({
Mike Greiling's avatar
Mike Greiling committed
320
      sourceMap: true
321 322 323
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') }
Mike Greiling's avatar
Mike Greiling committed
324
    })
325
  );
326

327
  // compression can require a lot of compute time and is disabled in CI
328
  if (!NO_COMPRESSION) {
329
    config.plugins.push(new CompressionPlugin());
330
  }
331 332 333
}

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

353 354 355 356 357 358 359 360 361 362 363 364
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'),
    })
  );
}

365
module.exports = config;