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

Updating Values in Nested Forms with Angular Reactive Form

I have been grappling with a form setup that looks something like this: itemEntities: [ {customisable: [{food: {..}, quantity: 1}, {food: {..}, quantity: 5}]}, {customisable: [{food: {..}, quantity: 0}]}, ] My challenge lies in trying to u ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

various issues with fonts and Uncaught Eval error

I've been encountering multiple font/style errors and an uncaught eval. I have attached a picture for reference. My Angular application is not functioning properly, and I suspect these errors may be the reason. However, I am unsure of their significan ...

Encountering difficulties when attempting to start a new project in Angular

I am encountering an issue while trying to create new in Angular, using version 6 and Node.js v8.11 Here is the console log: Unable to save binary /home/amit/demo/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...

What is the process of declaring a method within a subclass and then retrieving it from a method within the parent class using Typescript?

I am currently working with this TypeScript code snippet: abstract class Base { static actions:Record<string,unknown> static getActions () { return this.actions } } class Sub extends Base { static actions = { bar:(bar:string ...

Effective strategies for managing form submissions with React and Typescript

As I dive into refactoring my code to TypeScript, especially as I am still getting accustomed to it, I find myself pondering about the HTML element types with React events. This has led me to rethink how I approach form creation and submission event handli ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Instructions for accessing the side menu upon navigating to a new page

I'm working on an Ionic4 app that integrates with Google Firestore and includes a login feature. My goal is to have the sidemenu automatically open whenever a user logs into the application. For example: Login > PageX > *Open Sidemenu. How can I achi ...

Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice? The given URL structure is: /api/upload?file=${filename}&fileType=${fileType} This is the current file structure: app api upload ...

Error: The file bundle.js cannot be located. Please check your Web

[IMPORTANT UPDATE] The bundle.js file was actually created in memory. For smooth operation, it is advised to maintain index.html and bundle.js (configured in webpack.config.js) in the same directory to prevent any potential issues. I've been struggli ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...

Best Practices for Angular 4 Modules

I've been tackling a large project in Angular 4.3.6 and I'm exploring the optimal approach to organizing different navigation items into modules. All modules are loaded lazily. Here is an overview of the navigation: Administration Personal s ...

Saving information obtained through Angular subscribe into a variable

One of the services I have is called getWeather, which contains a method that communicates with an API using longitude and latitude parameters and then returns the response: import { Injectable } from '@angular/core'; import { HttpClient } from ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

Experimenting with an Angular 2 component using a simulated service

Currently, I am experimenting with testing an Angular2 component that relies on a service. In order to conduct the test effectively, I aim to provide a stubbed service. However, it appears that the test component does not recognize this stubbed service. ...

"Step-by-step guide on incorporating a CSS file into an Isomorphic React application using Webpack

Currently, I am working on developing an isomorphic react application that utilizes express, react, and webpack. The setup seems to be functioning properly until I try to import a CSS file within one of my components. From what I understand, Node has troub ...

Connecting Ag Grid with modules

Unable to link with modules as it's not a recognized attribute of ag-grid-angular <ag-grid-angular #agGrid style="width: 100%; height: 100%;" id="myGrid" class="ag-theme-balham" [modules]="modules" [columnDefs ...