What is the process for eliminating moment locales from an Angular build?

When I build my Angular 5 application with the command:

ng build --prod --sm

I noticed that the main.js file contains a lot of excess space occupied by moment. It seems all the locales are being loaded when I include:

import * as moment from 'moment';

Additionally, I have utilized material-moment-adapter for specific functionality in my app which also requires the moment package.

My application was created using angular-cli. I have come across several resources mentioning excluding locales via webpack.config.js settings. Is there a way to achieve this directly within angular-cli?

Answer №1

This article provides a great solution to the problem:

In summary:

  1. ng add ngx-build-plus

  2. Add a file webpack.extra.js in the root of your project:

    const webpack = require('webpack');
    module.exports = {
        plugins: [
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
        ]
    }
    
  3. Run:

    npm run build --prod --extra-webpack-config webpack.extra.js
    

Important Note: moment.js has been officially deprecated. https://momentjs.com/docs/#/-project-status/ (consider using day.js or luxon instead)

Answer №2

To achieve this without relying on external libraries, you can easily implement the following code snippet within the compilerOptions section of your tsconfig.json file:

"paths": {
  "moment": [
    "../node_modules/moment/min/moment.min.js"
  ]
}

Answer №3

If you are using Angular 12 or a more recent version

This solution didn't seem to work for me personally

const webpack = require('webpack');

module.exports = {
    plugins: [
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ]
}

However, this alternative did the trick for me

const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.IgnorePlugin({
      resourceRegExp: /^\.\/locale$/,
      contextRegExp: /moment$/
    })
  ]
};

Answer №5

When working with Angular 12, I took the following steps:

npm i --save-dev @angular-builders/custom-webpack

This allowed me to utilize a custom webpack configuration.

npm i --save-dev moment-locales-webpack-plugin
npm i --save-dev moment-timezone-data-webpack-plugin

Next, I made adjustments to my angular.json file as shown below:

    ...
    "architect": {
        "build": {
            "builder": "@angular-builders/custom-webpack:browser",
                "options": {
                    "customWebpackConfig": {
                        "path": "./extra-webpack.config.js"
                    },
                    ...

After that, in the extra-webpack.config.js file:

const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin');

module.exports = {
    plugins: [
        new MomentLocalesPlugin({
            localesToKeep: ['en-ie']
        }),
        new MomentTimezoneDataPlugin({
            matchZones: /Europe\/(Belfast|London|Paris|Athens)/,
            startYear: 1950,
            endYear: 2050,
        }),
    ]
};

You can customize the options above according to your requirements. This approach provides precise control over which locales and timezones are included, compared to using regular expressions found in other solutions.

Answer №6

Unfortunately, the previously suggested solutions didn't work for me as they were focused on the incorrect path (avoid using ../) in the tsconfig.app.json file.

{
...
   "compilerOptions": {
      "paths": {
        "moment": [
          "node_modules/moment/min/moment.min.js"
        ]
      }
   }
}

Thankfully, I found a working solution in Angular 12.2.X by making changes directly in the tsconfig.app.json file. This not only fixed the issue but also ensured that the IDE's type information worked correctly. https://i.stack.imgur.com/FJEDw.png

https://i.stack.imgur.com/NqAMz.png

It's crucial to avoid modifying the tsconfig.json file, as doing so could cause your IDE to lose important type information. https://i.stack.imgur.com/Qb6vY.png

This adjustment resolved the usage problem within both the app and the library. I verified this using source-map-explorer tool.

ng build --sourceMap=true --namedChunks=true --configuration production && source-map-explorer dist/**/*.js

https://i.stack.imgur.com/DdLJh.png

Answer №7

I encountered a similar issue with the momentjs library and was able to resolve it by taking the following steps:

Instead of using the IgnorePlugin to exclude the library, I utilized the ContextReplacementPlugin to specify which locale files should be included in the project.

  1. Follow all of the steps outlined in this answer:

  2. In your webpack.config.js file, include the following code snippet:

    const webpack = require("webpack");
    
    module.exports = {
        plugins: [
            new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /(en|fr)$/)
        ]
    };
    

By implementing this configuration, only the en and fr locale files will be added to your application's distribution folder.

Answer №8

If you're using Angular 9, consider switching to moment-mini-ts in place of moment

npm i moment-mini-ts

import * as moment from 'moment-mini-ts'

Remember to uninstall the original moment package

npm uninstall moment 

The transition to angular 9 should be smooth with this change

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

Exploring the Secrets of JSON Parsing in Angular

In my Angular application, I have the following JSON: var alphas = { "Data": { "1" : { "abc": { "key1":"Value1", "key2":"Value2", ...

Reusing observables after encountering errors

Is there a way to handle an Observable that errors out and stops emitting values in Angular templates? For instance, if I have a Subject that switches to an HTTP call using switchMap and the call fails due to incorrect user input. How do I ensure that the ...

Combine the information from 3 separate subscriptions into a single object using RxJS in Angular 9

I am seeking assistance with merging data from 3 different sensors into one object. I am using Cordova plugins to retrieve accelerometer, gyroscope, and magnetometer data. However, I am facing an issue in subscribing to all three observables simultaneously ...

Why isn't my Visual Studio updating and refreshing my browser after making changes to the Angular project?

Having added an Angular project and running it successfully with ng serve / npm start, I encountered an issue. After making changes to the project and saving them using ctrl+s or file/all save, the project server did not recompile and the browser did not ...

What is the best way to transfer PHP form data to an Angular2 application?

As I am still getting familiar with angular2/4, please bear with me if I overlook something obvious. I am currently working on updating a booking process using angular2/4. Initially, the booking procedure commences on a php website, and once some basic in ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

It seems that Angular2 Universal is experiencing some instability as it crashes frequently with the message "[nodemon] app crashed - waiting for file

After trying to work with the starter repo from my Angular class, I've found it to be quite unstable. It seems to be working locally when hitting the same service as remote, but I keep encountering errors. I have followed all the instructions: npm r ...

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Utilizing Angular 2's ViewChild within the <router-outlet> Tag

I've been working on a project using Angular 2. Within the MainComponent, I'm utilizing @ViewChild to reference child components. The MainComponent also contains a <router-outlet> where various components are loaded. My query is, how can I ...

The Validator.js module cannot be located - Unable to resolve 'http' in the client

Struggling with integrating the amadeus-node package into an angular 10 project. When I add the following line: const Amadeus = require('amadeus'); I encounter this error: ERROR in ./node_modules/amadeus/lib/amadeus/client/validator.js Module ...

Issue updating @angular/core in Angular CLI caused by rxjs dependency

Currently, I am in the process of updating angular and angular material to version 6. I have successfully updated the cli to allow for the new ng update command. However, when attempting to use it to update @angular/core, I encounter an error stating that ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Determine to which observable in the list the error corresponds

const obs1$ = this.service.getAllItems(); const obs2$ = this.service.getItemById(1); combineLatest([obs1$, obs2$]) .subscribe(pair => { const items = pair[0]; const item = pair[1]; // perform actions }, err => { // det ...

Inline styling for a Cypress test on an Angular component within an SVG markup

Testing out this SVG for a specific purpose, without needing to explain why. Running some tests on it! <svg class="custom-background" width="1864" height="441" style="background: linear-gradient(to right, rgb(255, 255, ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

Encountering a hiccup when working with Angular and npm

Error: The '@angular-devkit/build-angular:browser' builder's node package could not be located. Upon running npm start, the console displays this error message: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="473 ...

Issue with clearing subscription upon navigating to another page is not functioning as expected

Currently, I am working on building a basic search screen to gain a better understanding of Angular subscriptions, which I have found to be quite perplexing. On my home page, I have set up two components - one for filtering and the other for displaying sea ...

The error occurred while using NPM watch: ReferenceError: The variable "_" is not recognized in the file "../node_modules/angular-google-maps/dist/angular-google-maps.js" at line 1, column 1 (

I'm currently working with Angular and encountered an error in the console section of my browser after restarting my computer: Unhandled Promise rejection: _ is not defined ; Zone: <root> ; Task: Promise.then ; Value: ReferenceError: _ is not de ...

The Angular AOT compilation process is causing essential code to be stripped away from the openlayers

We have recently updated our project to use Angular 7 along with openlayers 5.3, and so far everything has been running smoothly. In an effort to improve initial loading times, we implemented several optimizations during the build process, including enabli ...