What are the differences between webpack development and production build modes?

后端 未结 1 1622
星月不相逢
星月不相逢 2021-02-14 16:55

In Grunt or Gulp, I used to define all the requirements myself, like: stuff should be minified only for production, livereload should be enabled only in dev server.

Webp

1条回答
  •  长情又很酷
    2021-02-14 17:41

    Shortcuts

    Like you said, -d is a shortcut for --debug --devtool source-map --output-pathinfo where:

    1. --debug activates debug mode for loaders and its behaviour depends on each loader. You can activate it via param { debug: true } in your webpack.config.js
    2. --devtool is basically allow to select type of sourcemaps for your files via param { devtool: "sourcemap" } or if you use webpack@2: { devtool: 'eval-cheap-module-source-map' }(See all options)
    3. --output-pathinfo will write original filepath into webpack's requires like this: __webpack_require__(/* ./src/containers/App/App.js */15).
      You can activate it via: { output: { pathinfo: true } }

    Second shortcut, -p stands for --optimize-minimize --optimize-occurence-order where:

    1. --optimize-minimize will add webpack.optimize.UglifyJsPlugin into your module plugins which will minify your code (remove spaces, mangle variable names and other optimizations)
    2. --optimize-occurence-order will add webpack.optimize.OccurenceOrderPlugin to plugin list which will assign your most used dependencies lower ids, so code will be smaller.

      For example: you have imported react in every file and webpack will try to require it like that __webpack_require__(1); instead of __webpack_require__(1266);

    Putting all together

    So, in your case if you have webpack.config.js, you can change it like this:

    var webpack = require('webpack');
    var webpackConfig = {
       // here goes your base config
    };
    
    // -d shortcut analogue
    if (process.env.NODE_ENV === 'development') {
      webpackConfig.debug = true;
      webpackConfig.devtool = 'sourcemap';
      webpackConfig.output.pathinfo = true;
    }
    
    // -p shortcut analogue
    if (process.env.NODE_ENV === 'production') {
      webpackConfig.plugins.push(new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production')
      }));
      webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin());
      webpackConfig.plugins.push(new webpack.optimize.OccurenceOrderPlugin());
    }
    
    module.exports = webpackConfig;
    

    If you want to look at actual parsing of these params, look at https://github.com/webpack/webpack/blob/master/bin/convert-argv.js#L19

    0 讨论(0)
提交回复
热议问题