How to Prevent Moment.Js from Loading Locales with Webpack

How to prevent moment.js from loading locales with webpack?

The code require('./locale/' + name) can use every file in the locale dir. So webpack includes every file as module in your bundle. It cannot know which language you are using.

There are two plugins that are useful to give webpack more information about which module should be included in your bundle: ContextReplacementPlugin and IgnorePlugin.

require('./locale/' + name) is called a context (a require which contains an expression). webpack infers some information from this code fragment: A directory and a regular expression. Here: directory = ".../moment/locale" regular expression = /^.*$/. So by default every file in the locale directory is included.

The ContextReplacementPlugin allows to override the inferred information i.e. provide a new regular expression (to choose the languages you want to include).

Another approach is to ignore the require with the IgnorePlugin.

Here is an example:

var webpack = require("webpack");
module.exports = {
// ...
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|hu/)
// new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
};

How to exclude moment locales from angular build?

This article describe good solution:
https://medium.jonasbandi.net/angular-cli-and-moment-js-a-recipe-for-disaster-and-how-to-fix-it-163a79180173

Briefly:

  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

    enter code here

Warning
moment.js has been deprecated officially
https://momentjs.com/docs/#/-project-status/ (try use day.js or luxon)



Related Topics



Leave a reply



Submit