webpack.config.js 10.5 KB
Newer Older
1 2 3
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
4
const VueLoaderPlugin = require('vue-loader/lib/plugin');
5 6
const StatsWriterPlugin = require('webpack-stats-plugin').StatsWriterPlugin;
const CompressionPlugin = require('compression-webpack-plugin');
7
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
P
Phil Hughes 已提交
8
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
9 10

const ROOT_PATH = path.resolve(__dirname, '..');
11
const CACHE_PATH = process.env.WEBPACK_CACHE_PATH || path.join(ROOT_PATH, 'tmp/cache');
12
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
P
Phil Hughes 已提交
13
const IS_DEV_SERVER = process.argv.join(' ').indexOf('webpack-dev-server') !== -1;
W
Winnie Hellmann 已提交
14
const IS_EE = require('./helpers/is_ee_env');
15 16
const DEV_SERVER_HOST = process.env.DEV_SERVER_HOST || 'localhost';
const DEV_SERVER_PORT = parseInt(process.env.DEV_SERVER_PORT, 10) || 3808;
17
const DEV_SERVER_LIVERELOAD = IS_DEV_SERVER && process.env.DEV_SERVER_LIVERELOAD !== 'false';
18 19
const WEBPACK_REPORT = process.env.WEBPACK_REPORT;
const NO_COMPRESSION = process.env.NO_COMPRESSION;
20
const NO_SOURCEMAPS = process.env.NO_SOURCEMAPS;
21

22 23 24
const VUE_VERSION = require('vue/package.json').version;
const VUE_LOADER_VERSION = require('vue-loader/package.json').version;

25 26
const devtool = IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map';

27 28
let autoEntriesCount = 0;
let watchAutoEntries = [];
29
const defaultEntries = ['./main'];
30 31 32

function generateEntries() {
  // generate automatic entry points
33
  const autoEntries = {};
34
  const autoEntriesMap = {};
M
Mike Greiling 已提交
35 36 37 38
  const pageEntries = glob.sync('pages/**/index.js', {
    cwd: path.join(ROOT_PATH, 'app/assets/javascripts'),
  });
  watchAutoEntries = [path.join(ROOT_PATH, 'app/assets/javascripts/pages/')];
39 40 41

  function generateAutoEntries(path, prefix = '.') {
    const chunkPath = path.replace(/\/index\.js$/, '');
42
    const chunkName = chunkPath.replace(/\//g, '.');
43
    autoEntriesMap[chunkName] = `${prefix}/${path}`;
44
  }
45

M
Mike Greiling 已提交
46
  pageEntries.forEach(path => generateAutoEntries(path));
47

48 49 50 51 52 53 54 55
  if (IS_EE) {
    const eePageEntries = glob.sync('pages/**/index.js', {
      cwd: path.join(ROOT_PATH, 'ee/app/assets/javascripts'),
    });
    eePageEntries.forEach(path => generateAutoEntries(path, 'ee'));
    watchAutoEntries.push(path.join(ROOT_PATH, 'ee/app/assets/javascripts/pages/'));
  }

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  const autoEntryKeys = Object.keys(autoEntriesMap);
  autoEntriesCount = autoEntryKeys.length;

  // import ancestor entrypoints within their children
  autoEntryKeys.forEach(entry => {
    const entryPaths = [autoEntriesMap[entry]];
    const segments = entry.split('.');
    while (segments.pop()) {
      const ancestor = segments.join('.');
      if (autoEntryKeys.includes(ancestor)) {
        entryPaths.unshift(autoEntriesMap[ancestor]);
      }
    }
    autoEntries[entry] = defaultEntries.concat(entryPaths);
  });
71

72
  const manualEntries = {
73
    default: defaultEntries,
M
Mike Greiling 已提交
74
    raven: './raven/index.js',
75 76 77 78 79
  };

  return Object.assign(manualEntries, autoEntries);
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
const alias = {
  '~': path.join(ROOT_PATH, 'app/assets/javascripts'),
  emojis: path.join(ROOT_PATH, 'fixtures/emojis'),
  empty_states: path.join(ROOT_PATH, 'app/views/shared/empty_states'),
  icons: path.join(ROOT_PATH, 'app/views/shared/icons'),
  images: path.join(ROOT_PATH, 'app/assets/images'),
  vendor: path.join(ROOT_PATH, 'vendor/assets/javascripts'),
  vue$: 'vue/dist/vue.esm.js',
  spec: path.join(ROOT_PATH, 'spec/javascripts'),

  // the following resolves files which are different between CE and EE
  ee_else_ce: path.join(ROOT_PATH, 'app/assets/javascripts'),
};

if (IS_EE) {
  Object.assign(alias, {
    ee: path.join(ROOT_PATH, 'ee/app/assets/javascripts'),
    ee_empty_states: path.join(ROOT_PATH, 'ee/app/views/shared/empty_states'),
    ee_icons: path.join(ROOT_PATH, 'ee/app/views/shared/icons'),
    ee_images: path.join(ROOT_PATH, 'ee/app/assets/images'),
    ee_spec: path.join(ROOT_PATH, 'ee/spec/javascripts'),
    ee_else_ce: path.join(ROOT_PATH, 'ee/app/assets/javascripts'),
  });
}

105
module.exports = {
M
Mike Greiling 已提交
106 107
  mode: IS_PRODUCTION ? 'production' : 'development',

108 109 110
  context: path.join(ROOT_PATH, 'app/assets/javascripts'),

  entry: generateEntries,
111 112 113 114

  output: {
    path: path.join(ROOT_PATH, 'public/assets/webpack'),
    publicPath: '/assets/webpack/',
115 116
    filename: IS_PRODUCTION ? '[name].[chunkhash:8].bundle.js' : '[name].bundle.js',
    chunkFilename: IS_PRODUCTION ? '[name].[chunkhash:8].chunk.js' : '[name].chunk.js',
117
    globalObject: 'this', // allow HMR and web workers to play nice
118 119
  },

120
  resolve: {
P
Phil Hughes 已提交
121
    extensions: ['.js', '.gql', '.graphql'],
122
    alias,
M
Mike Greiling 已提交
123 124
  },

M
Mike Greiling 已提交
125
  module: {
126
    strictExportPresence: true,
M
Mike Greiling 已提交
127
    rules: [
P
Phil Hughes 已提交
128 129 130 131 132
      {
        type: 'javascript/auto',
        test: /\.mjs$/,
        use: [],
      },
M
Mike Greiling 已提交
133
      {
134
        test: /\.js$/,
135
        exclude: path => /node_modules|vendor[\\/]assets/.test(path) && !/\.vue\.js/.test(path),
M
Mike Greiling 已提交
136
        loader: 'babel-loader',
137
        options: {
138
          cacheDirectory: path.join(CACHE_PATH, 'babel-loader'),
139
        },
F
Filipa Lacerda 已提交
140
      },
141 142
      {
        test: /\.vue$/,
M
Mike Greiling 已提交
143
        loader: 'vue-loader',
144 145 146 147 148 149 150 151 152
        options: {
          cacheDirectory: path.join(CACHE_PATH, 'vue-loader'),
          cacheIdentifier: [
            process.env.NODE_ENV || 'development',
            webpack.version,
            VUE_VERSION,
            VUE_LOADER_VERSION,
          ].join('|'),
        },
153
      },
P
Phil Hughes 已提交
154 155 156 157 158
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader',
      },
F
Filipa Lacerda 已提交
159 160
      {
        test: /\.svg$/,
M
Mike Greiling 已提交
161 162
        loader: 'raw-loader',
      },
S
Sam Rose 已提交
163
      {
164
        test: /\.(gif|png)$/,
S
Sam Rose 已提交
165
        loader: 'url-loader',
166
        options: { limit: 2048 },
S
Sam Rose 已提交
167
      },
P
Phil Hughes 已提交
168 169
      {
        test: /\_worker\.js$/,
170 171 172 173
        use: [
          {
            loader: 'worker-loader',
            options: {
174
              name: '[name].[hash:8].worker.js',
175
              inline: IS_DEV_SERVER,
176 177 178 179
            },
          },
          'babel-loader',
        ],
P
Phil Hughes 已提交
180
      },
M
Mike Greiling 已提交
181
      {
182
        test: /\.(worker(\.min)?\.js|pdf|bmpr)$/,
S
Sam Rose 已提交
183 184
        exclude: /node_modules/,
        loader: 'file-loader',
185
        options: {
186
          name: '[name].[hash:8].[ext]',
M
Mike Greiling 已提交
187
        },
S
Sam Rose 已提交
188
      },
189
      {
190
        test: /.css$/,
191
        use: [
192
          'vue-style-loader',
193
          {
194 195
            loader: 'css-loader',
            options: {
196
              name: '[name].[hash:8].[ext]',
M
Mike Greiling 已提交
197
            },
198 199 200 201 202 203 204 205
          },
        ],
      },
      {
        test: /\.(eot|ttf|woff|woff2)$/,
        include: /node_modules\/katex\/dist\/fonts/,
        loader: 'file-loader',
        options: {
206
          name: '[name].[hash:8].[ext]',
M
Mike Greiling 已提交
207
        },
208
      },
209
    ],
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  },

  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      maxInitialRequests: 4,
      cacheGroups: {
        default: false,
        common: () => ({
          priority: 20,
          name: 'main',
          chunks: 'initial',
          minChunks: autoEntriesCount * 0.9,
        }),
        vendors: {
          priority: 10,
          chunks: 'async',
          test: /[\\/](node_modules|vendor[\\/]assets[\\/]javascripts)[\\/]/,
        },
        commons: {
          chunks: 'all',
          minChunks: 2,
          reuseExistingChunk: true,
        },
      },
    },
M
Mike Greiling 已提交
236 237
  },

238 239 240
  plugins: [
    // manifest filename must match config.webpack.manifest_filename
    // webpack-rails only needs assetsByChunkName to function properly
241 242 243
    new StatsWriterPlugin({
      filename: 'manifest.json',
      transform: function(data, opts) {
244
        const stats = opts.compiler.getStats().toJson({
245 246 247 248
          chunkModules: false,
          source: false,
          chunks: false,
          modules: false,
M
Mike Greiling 已提交
249
          assets: true,
250 251
        });
        return JSON.stringify(stats, null, 2);
M
Mike Greiling 已提交
252
      },
P
Phil Hughes 已提交
253
    }),
M
Mike Greiling 已提交
254

255 256 257
    // enable vue-loader to use existing loader rules for other module types
    new VueLoaderPlugin(),

258 259 260
    // automatically configure monaco editor web workers
    new MonacoWebpackPlugin(),

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

264 265 266 267 268 269
    // fix legacy jQuery plugins which depend on globals
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
    }),

270 271 272 273 274 275
    new webpack.NormalModuleReplacementPlugin(/^ee_component\/(.*)\.vue/, function(resource) {
      if (Object.keys(module.exports.resolve.alias).indexOf('ee') >= 0) {
        resource.request = resource.request.replace(/^ee_component/, 'ee');
      } else {
        resource.request = path.join(
          ROOT_PATH,
276
          'app/assets/javascripts/vue_shared/components/empty_component.js',
277 278 279 280
        );
      }
    }),

281 282
    // compression can require a lot of compute time and is disabled in CI
    IS_PRODUCTION && !NO_COMPRESSION && new CompressionPlugin(),
283

284 285 286 287 288 289 290 291
    // WatchForChangesPlugin
    // TODO: publish this as a separate plugin
    IS_DEV_SERVER && {
      apply(compiler) {
        compiler.hooks.emit.tapAsync('WatchForChangesPlugin', (compilation, callback) => {
          const missingDeps = Array.from(compilation.missingDependencies);
          const nodeModulesPath = path.join(ROOT_PATH, 'node_modules');
          const hasMissingNodeModules = missingDeps.some(
292
            file => file.indexOf(nodeModulesPath) !== -1,
293
          );
294

295 296 297 298 299
          // watch for changes to missing node_modules
          if (hasMissingNodeModules) compilation.contextDependencies.add(nodeModulesPath);

          // watch for changes to automatic entrypoints
          watchAutoEntries.forEach(watchPath => compilation.contextDependencies.add(watchPath));
300

301 302
          // report our auto-generated bundle count
          console.log(
303
            `${autoEntriesCount} entries from '/pages' automatically added to webpack output.`,
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
          );

          callback();
        });
      },
    },

    // enable HMR only in webpack-dev-server
    DEV_SERVER_LIVERELOAD && new webpack.HotModuleReplacementPlugin(),

    // optionally generate webpack bundle analysis
    WEBPACK_REPORT &&
      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'),
      }),
323 324 325 326

    new webpack.DefinePlugin({
      'process.env.EE': JSON.stringify(IS_EE),
    }),
327 328 329
  ].filter(Boolean),

  devServer: {
330
    host: DEV_SERVER_HOST,
331
    port: DEV_SERVER_PORT,
332
    disableHostCheck: true,
333 334 335 336
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
    },
337
    stats: 'errors-only',
S
Simon Knox 已提交
338
    hot: DEV_SERVER_LIVERELOAD,
M
Mike Greiling 已提交
339
    inline: DEV_SERVER_LIVERELOAD,
340
  },
341

342
  devtool: NO_SOURCEMAPS ? false : devtool,
343

344 345 346
  // sqljs requires fs
  node: { fs: 'empty' },
};