Search code examples
reactjswebpackbundlewebpack-bundle-analyzer

How to make sure node_modules is not included in bundle


I am using webpack-bundle-analyzer to identify packages that might need to be optimised. My webpack config excludes node_modules

webpack.config

  config.module = {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: [
        /node_modules/,
        /firebase-functions/,
        /tests/
      ],
      use: {
        loader: 'babel-loader'
      }
    },
    ...
   }]
 }

When I look at the representation of my bundle, I can still see node_modules, does that mean node_modules is included in my bundle?

I first run yarn run build:stats to generate the compilation-stats.json and then yarn run analyse

package.json

  "scripts": {
    "build:prod": "cross-env NODE_ENV=production webpack -p --env production",
    "dev-server": "cross-env NODE_ENV=development ANALYSE_BUNDLE=no webpack-dev-server --host 127.0.0.1 --port 8080",
    "dev-server-analyse": "cross-env NODE_ENV=development ANALYSE_BUNDLE=yes webpack-dev-server --host 127.0.0.1 --port 8080",
    "build:stats": "cross-env NODE_ENV=production webpack --profile --json --env=production > compilation-stats.json",
    "analyse": "webpack-bundle-analyzer compilation-stats.json dist",

I have also tried to instruct to not include node_modules

webpack.config

new BundleAnalyzerPlugin({
  excludeAssets: ['node_modules'],
  statsOptions: {
    exclude: /node_modules/
  }
})

The result from webpack-bundle-analyzer enter image description here So, Is node_modules is included in my bundle or am I simply doing something wrong?

Kind regards /K


Solution

  • Yes it is. WebPack rules just describe loaders chain to be used. The pure JS code is included any way. There is a number of reasons why you could exclude vendor code from your bundle like:

    • rebuild time optimization
    • best caching
    • etc

    WebPack providing different ways to do it:

    WebPack has default chunk optimizator. In most of cases it is enough for good results. You should do some other manual optimization only in case when you face some real problem and understand what do you want to chive.