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:
ng add ngx-build-plus
Add a file webpack.extra.js in the root of your project:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
]
}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
Referenceerror: Document Is Not Defined (In Plain JavaScript)
Jquery-Ui-Dialog - How to Hook into Dialog Close Event
What Is the $$ (Double Dollar Sign) Used for in Angular
Can't Access Cookies from Document.Cookie in Js, But Browser Shows Cookies Exist
Jquery's Live() Is Deprecated. What Do I Use Now
How to Get All Checked Checkboxes
How to Populate the Options of a Select Element in JavaScript
D3 Appending Text to a Svg Rectangle
How to Access Xhr Responsebody (For Binary Data) from JavaScript in Ie
How to Resolve Typeerror: Cannot Convert Undefined or Null to Object
Dynamic Variables Names in JavaScript
Es6 Modules Implementation, How to Load a JSON File
Fetching Values from Email in Protractor Test Case
Package.JSON' Is Not Under 'Rootdir'
Is There a JavaScript Strcmp()