Webpack imports all the unused exports into the bundle

1k views Asked by At

I have several webpack configs with different entry points for building different bundles, and some of them share some of the modules. I'm trying to get the unused exports tree-shaken, but with the following setup, my bundles end up having ALL the exports inside, from every possible module, even though most of them are not imported anywhere. What am I doing wrong?

'index.ts' is used as an example for one of those entry points.

folder structure:

src/
    /shared-modules
    ...
    index.ts
    other.ts
    ...

webpack.config.js:

{
  entry: {
    index: './src/index.ts',
  },
  output: {
    path: path.resolve(__dirname, `dist/${ env }`),
      filename: 'index.js'
    },
    module: {
      rules: [
        {
          test:/\.ts$/i,
          include: path.resolve(__dirname, 'src'),
          use: ['babel-loader', 'ts-loader'],
          exclude: /node_modules/
        }
      ]
    },
    resolve: {
      extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    mode: 'production',
    optimization: {
      usedExports: true,
      minimize: true,
      minimizer: [
        new TerserPlugin()
      ]
    }
  }
}

.babelrc:

{
  "presets": [
      [
          "@babel/preset-env",
          {
              "modules": false
          }
      ]
  ]
}

tsconfig.json:

{
  "files": [
    "src/index.ts",
    "src/other.ts"
  ],
  "compilerOptions": {
    "module": "ES6",
    "moduleResolution": "Node",
    "target": "ES5",
    "sourceMap": true,
    "lib": ["ES2015", "ES2017", "DOM"]
  },
  "exclude": [
    "node_modules"
  ]
}

package.json:

{
  "name": "script",
  "type": "commonjs",
  ...
  "sideEffects": [
    "./src/index.ts"
  ],
  ...
}
1

There are 1 answers

0
rookieeee On

You may need to setup sideEffects in your package.json. for example:

{
  "name": "your-project",
  "sideEffects": false
}

If your code did have some side effects though, an array can be provided instead:

{
  "name": "your-project",
  "sideEffects": ["./src/some-side-effectful-file.js"]
}