如何运行webpack-bundle-analyzer

时间:2018-05-09 18:54:06

标签: webpack webpack-dev-server webpack-2

我安装了webpack-bundle-analyzer并需要运行它。我该怎么做?我有几个错误。其中最常见的是

Could't analyze webpack bundle

2 个答案:

答案 0 :(得分:12)

最后我发现可以通过两种方式解决这个问题。 See more。无论如何,您需要添加到 webpack.config.js

var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

plugins : [ 
  new BundleAnalyzerPlugin({
    analyzerMode: 'server',
    generateStatsFile: true,
    statsOptions: { source: false }
  }),
  ...
],  

然后,如果您想在每次进行构建时查看浏览器中的报告html页面,则无需执行任何操作。

如果您想使用CLI不时运行报告页面,则需要在 webpack.config.js 中禁用服务器,如下所示:

plugins : [ 
  new BundleAnalyzerPlugin({
    analyzerMode: 'disabled',
    generateStatsFile: true,
    statsOptions: { source: false }
  }),
  ...
],

并在 package.json 的脚本部分添加行:

"scripts": {
  "bundle-report": "webpack-bundle-analyzer --port 4200 dist/stats.json",
  ...
}

我做了第二个选择。

答案 1 :(得分:0)

我的设置如下,看起来更简洁一些。关注此very nice tutorial about Webpack Visualization

webpack.config.js

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

webpackConfig.plugins = [
  new BundleAnalyzerPlugin({
    // use value from environment var STATS or 'disabled'
    analyzerMode: process.env.STATS || 'disabled',
  }),
];

package.json

"scripts": {
  "start": "APP_ENV=local PORT=443 webpack-dev-server --config webpack/webpack.config.js",
  "build": "npm run clean && webpack --config webpack/webpack.config.js --
  "stats": "STATS=server npm run build"
},