webpack config with optional usage of BundleAnalyzerPlugin

1.2k views Asked by At

I'm using webpack for a React project and would like to include the WebpackBundleAnalyzer, but only when explicitly specified in the npm script (e.g., npm run build --withReport true). By default, I don't want it to run.

My build script in package.json is straightforward:

"build": "webpack --mode production",

As are are the relevant snippets from my webpack.config.js:

...
const withReport = process.env.npm_config_withReport || 'false';
...
plugins: [
  ...
  withReport ? new BundleAnalyzerPlugin() : '',
],
...

My thought is that withReport will be false unless I specify otherwise (e.g., npm run build --withReport true), thus the BundleAnalyzer will not execute if I leave that off (npm run build).

Instead, the analyzer executes even if I don't specify --withReport. What am I missing?

1

There are 1 answers

0
Woodchuck On BEST ANSWER

I fixed this by making a couple changes to my webpack.config.js.

First I changed the way I declare withReport. Then I changed the way I instantiate BundleAnalyzerPlugin, to instead use concat after the other plugins:

...
const withReport = process.env.npm_config_withReport ? true : false;
...
plugins: [
  ...
].concat(withReport ? [new BundleAnalyzerPlugin()] : []),
...