Journey to webpack, part 6 – moment.js

webpack + Moment.js

Moment.js is a powerful library that lets you “parse, validate, manipulate, and display dates and times in JavaScript”. Despite the recent emergence of other libraries like fecha and date-fns, Moment.js has reigned for a long time as the go to library for manipulating dates in JavaScript. Please do check out the features of these other lightweight alternatives if you have the opportunity. Unfortunately we are fairly entrenched with Moment because we’re working with a 3 year old code base. “It is, what it is”, so we just have to deal with it.

onto the problem

Our initial problem was that we couldn’t even get webpack to build moment into the bundle: from webpack-config/vendor.ts:

1
import '../node_modules/moment/min/moment-with-locales';

grunt shell:webpackDev resulted in:

1
2
3
4
WARNING in ./node_modules/moment/min/moment-with-locales.js
Module not found: Error: Can't resolve './locale' in '/Users/oloreb/dev/redbox-pay/redbox\_angular/node\_modules/moment/min'
@ ./node_modules/moment/min/moment-with-locales.js 263:16-43
@ ./webpack-config/vendor.ts

The quick fix was to ignore the locale resolution, because moment-with-locales.js already had them:

1
new webpack.IgnorePlugin(/\\.\\/locale$/, /moment\\/min/)

But after looking at the BundleAnalyzer, we realized we were bringing in way too many locales. Much has been written about how to do this, so we stood on the shoulders of the giants and made the following changes: We tweaked vendor.ts to include moment instead of moment-with-locale and replaced the IgnorePlugin with this

1
new webpack.ContextReplacementPlugin(/moment\[\\/\\\\]locale$/, /en|fr|es|zh|pt|nl|de|it/),

and now our analyzer output looks like this:

140k to 29k !

And that’s the gzip comparison! SHIP IT! A quick update to our TODO list:

  1. Create vendor.min.js
  2. Create app-components.min.js
  3. Create app.min.js
  4. Create templates.app.min.js
  5. Try out webpack 3.0!
  6. Figure out what’s up with moment.js
  7. Use the webpack’d files in karma for unit tests
  8. Try the CommonChunksPlugin
  9. Handle CSS/LESS/SASS
  10. Use the dev-server instead of grunt-contrib-connect