Optimize moment.js size using webpack

16 Jun 2017
Moment.js library allows to parse, convert, format and display datetime in Javascript. It support converting datetime to particular locale and handle datetime based on timezone. It has rich support for showing datetime in around 100 languages. Many JavaScript datepicker, calander components use moment.js as the defacto solution to handle date-time conversions reliably. It offers support for Nodejs environment as well as client browsers.
The greater support for varying locale comes up with a price. The gziped size of the core library is approx. 16KB, where as core with locales it comes around 64KB ( 4 times the core library). GZip compression couldn't help much as the characters from each languages are unique. So a simple novice require statement using webpack would pull entire library along with all locale and blot your JavaScript bundle.
Novice import:
import * as moment from 'moment';
When you run webpack-bundle-analyzer you will something crazy as below
Moment.js with all locale included in bundle
As most projects are developed for targeted languages, so it doesn't require all locales to be loaded. So, it is sensible to require just the required one.
Webpack has ContextReplacementPlugin, that allows us to configure what to require or includer using RegEx (Regular expression). so modify your WebpackConfig.json to import just the en locales with below script
var ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');

plugins: [
...,
new ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
...]

Now re-run the webpack build and see the analyzer output. It should look similar to below with size approx. 17KB which is way too better.

moment.js with en locales

Reference:

https://webpack.js.org/plugins/context-replacement-plugin/

and My experience ;)

Related Posts