Since the Moment. js package isn't modularized and, per the threads on Github issues, it won't be done as support is ending and they have termed it a legacy project. This is the primary reason behind those large chunks in the build size.
You set locale with moment. locale('de') , and you create a new object representing the date of now by moment() (note the parenthesis) and then format('LLL') it. The parenthesis is important.
By default, Moment. js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.
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$/)
]
};
In our project, I include moment like this: import moment from 'moment/src/moment';
and that seems to do the trick. Our usage of moment is very simple though, so I'm not sure if there will be any inconsistencies with the SDK. I think this works because WebPack doesn't know how to find the locale files statically, so you get a warning (that's easy to hide by adding an empty folder at moment/src/lib/locale/locale
) but no locale includes.
UPDATE: 2021
There are many other libs that you may want to checkout:
ORIGINAL ANSWER:
Seems like the proper modular moment
library will never come up However, I just ended up of using https://github.com/ksloan/moment-mini like import * as moment from 'moment-mini';
Based on Adam McCrmick's answer, you were close, change your alias to:
resolve: {
alias: {
moment: 'moment/src/moment'
},
},
With webpack2
and recent versions of moment you can do:
import {fn as moment} from 'moment'
And then in webpack.config.js
you do:
resolve: {
packageMains: ['jsnext:main', 'main']
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With