LppEdd
LppEdd

Reputation: 21134

Webpack TerserPlugin - exclude node module

Using a custom Angular Builder, I'm trying to exclude an entire module from minification/optimization.

The Webpack .md file says

exclude
Type: String|RegExp|Array Default: undefined

Files to exclude.

Can I use this setting to exclude an entire directory (which is the node module)?


The current code is

export default class CustomizeTerserBrowserBuilder extends BrowserBuilder {
  public buildWebpackConfig(root: any, projectRoot: any, host: any, options: any): any {
    const webpackConfig = super.buildWebpackConfig(root, projectRoot, host, options);

    if (
      webpackConfig.optimization &&
      webpackConfig.optimization.minimizer &&
      Array.isArray(webpackConfig.optimization.minimizer)
    ) {
      const terserPlugin = (webpackConfig.optimization.minimizer as any[]).find(
        minimizer => minimizer instanceof TerserPlugin
      );

      if (terserPlugin) {
        terserPlugin.options.exclude = [/node_modules/];
      }
    }

    return webpackConfig;
  }
}

Upvotes: 2

Views: 7202

Answers (2)

apfel
apfel

Reputation: 101

Had the exact same issue on production with Webpack5, ended up going with something like following which will exclude specific files under node_modules or dist which cause Terser's "aggressive" minification attempts to break.

optimization: {
    minimize: NODE_ENV !== 'development', //only minimize on production
    //JS minimizer when "minimize === true",
    minimizer: [
        new TerserPlugin({
            test: /\.js$/,
            exclude: /(?:node_modules|dist)\/(update-notifier|numeral|jackspeak|bulma-extensions)\//, //whatever causes u a problem, either as RegExp or as a string[]
            terserOptions: {
                parse: {
                    bare_returns: true //allow code with returns outside of functions, solved a ton of issues.
                },
            },
        })],
    // rest of config.
    // ...

}

To be honest I'm not sure if excluding ALL files under /node_modules is a good idea.

Upvotes: 1

Tony
Tony

Reputation: 20102

Maybe you are looking for this

   module.exports = {
      optimization: {
        minimizer: [
          new TerserPlugin({
            exclude: /node_modules/,
          }),
        ],
      },
    };

Upvotes: 4

Related Questions