Skip to content
Explaining how to optimize the large bundle size of moment.js with webpack
JavaScript
Branch: master
Clone or download
Pull request Compare This branch is 2 commits behind jmblog:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
contextReplacementPlugin
default
ignorePlugin
.gitignore
.prettierignore
README.md
index.js
package-lock.json
package.json
source-map-explorer.png

README.md

How to optimize moment.js with webpack

When you write var moment = require('moment') in your code and pack with webpack, the size of the bundle file gets heavyweight because it includes all locale files.

To optimize the size, the two webpack plugins are available:

  1. IgnorePlugin
  2. ContextReplacementPlugin

Using IgnorePlugin

You can remove all locale files with the IgnorePlugin.

const webpack = require('webpack');
module.exports = {
  //...
  plugins: [
    // Ignore all locale files of moment.js
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
};

And you can still load some locales in your code.

const moment = require('moment');
require('moment/locale/ja');

moment.locale('ja');
...

This solution is used in create-react-app.

Using ContextReplacementPlugin

If you want to specify the including locale files in the webpack config file, you can use ContextReplacementPlugin.

const webpack = require('webpack');
module.exports = {
  //...
  plugins: [
    // load `moment/locale/ja.js` and `moment/locale/it.js`
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /ja|it/),
  ],
};

In this case, you don't need load the locale files in your code.

const moment = require('moment');
moment.locale('ja');
...

Measurements

  • webpack: v3.10.0
  • moment.js: v2.20.1
File size Gzipped
Default 266 kB 69 kB
w/ IgnorePlugin 68.1 kB 22.6 kB
w/ ContextReplacementPlugin 68.3 kB 22.6 kB

Bonus

date-fns is an alternative libraly to moment.js. It doesn't need this kind of tricky solution and has more benefits. It's worth considering.

References

You can’t perform that action at this time.