7

这是我的 webpack 设置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;


const SOURCE_DIR = './src';
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: SOURCE_DIR + '/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = env => {
  console.log(`Environment Configs: ${JSON.stringify(env) || 'Default'}`);
  console.log(`
  Available Configs:
  --env.watch = true / false //for allow webpack to watch build
  `)
  let environment = env || {};
  const {
    watch,
    analyze,
  } = environment;

  const configedAnalyzer = new BundleAnalyzerPlugin({
    // Can be `server`, `static` or `disabled`.
    // In `server` mode analyzer will start HTTP server to show bundle report.
    // In `static` mode single HTML file with bundle report will be generated.
    // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`.
    analyzerMode: 'static',//was server
    // Host that will be used in `server` mode to start HTTP server.
    analyzerHost: '127.0.0.1',
    // Port that will be used in `server` mode to start HTTP server.
    analyzerPort: 9124,
    // Path to bundle report file that will be generated in `static` mode.
    // Relative to bundles output directory.
    reportFilename: './../report/bundle_anlaysis.html',
    // Module sizes to show in report by default.
    // Should be one of `stat`, `parsed` or `gzip`.
    // See "Definitions" section for more information.
    defaultSizes: 'stat',
    // Automatically open report in default browser
    openAnalyzer: Boolean(analyze),
    // If `true`, Webpack Stats JSON file will be generated in bundles output directory
    generateStatsFile: Boolean(analyze),
    // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
    // Relative to bundles output directory.
    statsFilename: 'stats.json',
    // Options for `stats.toJson()` method.
    // For example you can exclude sources of your modules from stats file with `source: false` option.
    // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
    statsOptions: null,
    // Log level. Can be 'info', 'warn', 'error' or 'silent'.
    logLevel: 'info'
  });

  return {
    entry: SOURCE_DIR + '/index.js',
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: 'bundle.js',
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['env', 'react']
            }
          }
        }
      ]
    },
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    watch: Boolean(watch),
    plugins: [HtmlWebpackPluginConfig, configedAnalyzer], //
    devServer: {
      contentBase: path.join(__dirname, "dist"),
      compress: false,
      port: 9123,
    }
  };
}

当我这样做时,webpack -p文件大小要小得多,但是这个 react-dom.development.js 占据了几乎 50% 的大小,在我的情况下,是 1.1ish MB 中的 500ish KB。

在这里报告:

在此处输入图像描述

要查看报告的演示及其运行方式,您可以查看存储库。

注意:即使我添加NODE_ENV=production,大小更小,但开发 JavaScript 文件仍然存在!

4

1 回答 1

12

您的应用程序的process.env.NODE_ENV变量需要production在 webpack 的构建脚本中设置。React 的Optimizing Performance文档指导 webpack 用户使用 webpack 的DefinePlugin来做到这一点。

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify('production')
})

虽然该-p选项似乎应该设置process.env.NODE_ENVproduction,但在 Webpack 的指定环境文档中解释了一个警告,即这不是在webpack的构建脚本中设置的(对于它的价值,许多开发人员将此报告为一个问题)。

于 2018-01-09T21:56:29.523 回答