Webpack在小项目中创建大文件

24

我的webpack生成了一个很大的main.js文件(1.7mb),但这只是一个不到100行代码的小项目,包含20-30个文件。所需的依赖关系很少(React, Fluxible),而且我正在使用我能理解的每一个优化插件:

module.exports = {
  output: {
    path: './build',
    publicPath: '/public/',
    filename: '[name].js'
  },
  debug: false,
  devtool: 'eval',
  target: 'web',
  entry: [
  'bootstrap-sass!./bootstrap-sass.config.js',
  './client.js',
  ],
  stats: {
    colors: true,
    reasons: false
  },
  resolve: {
    extensions: ['', '.js'],
    alias: {
      'styles': __dirname + '/src/styles',
      'components': __dirname + '/src/scripts/components',
      'actions': __dirname + '/src/scripts/actions',
      'stores': __dirname + '/src/scripts/stores',
      'constants': __dirname + '/src/scripts/constants',
      'mixins': __dirname + '/src/scripts/mixins',
      'configs': __dirname + '/src/scripts/configs',
      'utils': __dirname + '/src/scripts/utils'
    }
  },
  module: {
    loaders: [
      { test: /\.css$/, loader: 'style!css' },
      { test: /\.js$/, exclude: /node_modules/, loader: require.resolve('babel-loader') },
      { test: /\.json$/, loader: 'json-loader'},
      { test: /\.(png|svg|jpg)$/, loader: 'url-loader?limit=8192' },
      { test: /\.(ttf|eot|svg|woff|woff(2))(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?name=/[name].[ext]"},
      { test: /\.scss$/,
        loader: ExtractTextPlugin.extract('style-loader',
          'css!sass?outputStyle=expanded&' +
          "includePaths[]=" +
          (path.resolve(__dirname, "./node_modules"))
          )
      }
    ]
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "windows.jQuery": "jquery"
    }),
    new ExtractTextPlugin("[name].css", {allChunks: true}),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.AggressiveMergingPlugin()
  ],

};

我做错了什么或者在哪里可以进一步提高文件大小?

3个回答

15

通过这些方法(devtools:'source-map'),以及使用默认设置的uglifyjs(不需要gzip时大约为670kb),我成功将我的React文件从2.1mb减小到了160kb(gzipped)。

虽然可能还不算非常优秀,但至少不再过于臃肿。

以下是我的webpack配置,仅供参考:

// webpack.config.js
var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: [
        'webpack-dev-server/client?http://127.0.0.1:2992',
        'webpack/hot/only-dev-server',
        './js/main'
    ],
    output: {
        path: './out/',
        filename: 'main.js',
        chunkFilename: '[name]-[chunkhash].js',
        publicPath: 'http://127.0.0.1:2992/out/'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['react-hot', 'babel?optional=runtime&stage=0&plugins=typecheck']
            }
        ]
    },
    progress: true,
    resolve: {
        modulesDirectories: [
            'js',
            'node_modules'
        ],
        extensions: ['', '.json', '.js']
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
        new webpack.DefinePlugin({
            'process.env': {
                // This has effect on the react lib size
                'NODE_ENV': JSON.stringify('production'),
            }
        }),
        new webpack.optimize.UglifyJsPlugin()
    ]
};

1
我的项目生成的文件大小与你的类似,同样不算太大,但是我的网站上几乎没有什么内容,所以我期望文件大小仍然会小得多。我在这里提供链接;请查看其中的 package.json 文件,看看你的项目是否也使用了可能占用大量空间的内容:https://github.com/amcsi/szeremi/tree/f93671a - Attila Szeremi
我在我的生产版本中移除了HotModuleReplacementPlugin插件。 - P.Brian.Mackey

10

你应该至少设置

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      // This has effect on the react lib size
      'NODE_ENV': JSON.stringify('production'),
    }
  }),
  ...
],

这将对React有很大帮助。

此外,在生产环境中将devtool设置为source-map更可取。有关更多信息,请参见官方文档

您可以尝试使用分析工具检查输出。要获取它所需的JSON,您需要执行类似于webpack --json > stats.json的操作,然后将stats.json传递给该工具。那可能会给你一些见解。


是的,我一定会看看这个并查看它如何影响代码。此外,我发现了我的错误,建议将其添加到答案中,我正在执行 devtools: true,这导致我的文件非常大,而对于生产环境来说,它不需要为真。 - Mohamed El Mahallawy
1
太酷了,我添加了那个。完全忘记了devtool - Juho Vepsäläinen
一个webpack捆绑分析的替代命令行工具: https://github.com/robertknight/webpack-bundle-size-analyzer - jmu

8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接