Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process.

According to the Webpack .md file:

exclude
Type: String|RegExp|Array Default: undefined

This setting is used to specify files to be excluded.

My question is, can I use this setting to exclude an entire directory (like the node module)?


This is the code snippet I am currently using:

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;
  }
}

Answer №1

Perhaps this is the solution you seek

   const configuration = {
      optimization: {
        minimizer: [
          new TerserPlugin({
            exclude: /node_modules/,
          }),
        ],
      },
    };

Answer №2

Encountered a similar issue on our production environment when using Webpack5. As a solution, I opted for the following approach to exclude specific files within the node_modules or dist directories. These exclusions prevent Terser's aggressive minification attempts from causing issues.

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)\//, //specify problematic files as RegExp or string[]
            terserOptions: {
                parse: {
                    bare_returns: true //allow code with returns outside of functions, resolved numerous issues.
                },
            },
        })],
    // rest of config.
    // ...

}

I'm unsure if excluding ALL files under /node_modules is the best approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using the makeStyles hook in a function component with React, Material-UI, and Typescript, an Invalid Hook Call error may

I'm feeling lost and frustrated with my current coding issue. Despite following the guidelines in the (javascript) documentation, I keep encountering the dreaded Invalid Hook Call error. My setup includes TypeScript 4.1.2, React 17.0.1, and React Typ ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

"Learn how to dynamically change the color of a button in Angular after it has been clicked

Can someone assist me in changing the button color to red after it has been clicked? I am looking for guidance on how to achieve this. The current code snippet is as follows: <td> <button mat-icon-button color="primary"> <m ...

What could be causing the error within the 'react-code-blocks' library?

Currently, I am involved in a project that utilizes Typescript and React. However, I have encountered an issue while working with the 'react-code-blocks' library. The structure of my container component is as follows: interface ICodeBlockProps { ...

Is there a way to prompt the compiler to generate an error when a type cannot be set to `undefined`

I'm working with a type called ILoadedValue<TValue>, which acts as a wrapper for types that can potentially be undefined. However, I want to prevent situations where TValue cannot be undefined, as it's more efficient to use the actual value ...

Unable to loop through the data using forEach method as it is not a function. Can anyone guide me on how to

Currently, I am working on an angular project that involves retrieving data from a JSON object. Typically, in such cases, I would create a class like 'fake.ts' to fetch and access the correct values. However, in this instance, the JSON contains 4 ...

Ineffectiveness of ngFor in displaying content within a component in Ionic 5

Feeling a bit overwhelmed here, I've successfully created a new component and it's working perfectly. Now I want to use this component on two different pages. To make things easier, I decided to create a component module (/components/all-compone ...

Utilizing combinedReducers will not prompt a re-render when dispatching actions

When I refrain from using combineReducers: const store = createStore<StoreState,any,any,any>(pointReducer, { points: 1, languageName: 'Points', }); function tick() { store.dispatch(gameTick()); requestAnimationFrame(tick) ...

How can I interpret the logs to troubleshoot sourceMap errors in a fresh Nextjs web application?

After completing a website following the Next.js tutorial here, I started adding tweaks and extra features. Unexpectedly, an irritating warning started popping up in the console: next-dev.js?3515:20 Warning: Function components cannot be given refs. Attem ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

Bidirectional data binding on the table

I am struggling to implement two-way data binding in a table between my .ts and my .html files. I have a structure that adds a new equipment to the array, and I want that new equipment to display on the table within the same screen. I believe it involves ...

How to use RxJs BehaviorSubject in an Angular Interceptor to receive incoming data

Being a newcomer to rxjs, I grasp most operators except for the specific use case involving BehaviorSubject, filter, and take. I am working on renewing an oauth access and refresh token pair within an Angular interceptor. While reviewing various codes fro ...

When deciding between StoreModule.forRoot and StoreModule.forFeature, consider the specific needs of your application

After researching, I discovered that the .forRoot function merges all reducers, allowing you to manipulate multiple reducers simultaneously when manipulating the state. On the other hand, the .forFeature function gives you the ability to manipulate each r ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

What is the best approach for defining variables in typescript?

Let's talk about creating a variable for a car: export class ICar { wheels: number; color: string; type: string; } So, which way is better to create the variable? Option one: const car = { wheels: 4, color: 'red', type: &apos ...

How to Eliminate Lower Borders from DataGrid Component in Material UI (mui)

I've been trying to customize the spacing between rows in a MUI Data Grid Component by overriding the default bottom border, but haven't had much success. I've experimented with different approaches such as using a theme override, adding a c ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

Array of colors for Wordcloud in Angular Highcharts

I am currently utilizing Angular Highcharts 9.1.0 and facing an issue with generating a word cloud that incorporates specific colors. Despite including color values in the array, they do not seem to be applied as intended. Take a look at the code snippet b ...

Using API data to dynamically set the background image in Angular 7

I am currently facing an issue with setting background images for cards that are populated with data from an API. Each card pulls specific information and I would like to use an image associated with that data as the background image for each card. <di ...