Moment.js - Reduce Webpack Bundle Size


Working with Javascript using Vanilla Javascript can be tricky sometimes. Especially, when introducing different time zone support to an application.

A very good library helping with date handling is Moment.js. Unfortunately, when bundling moment.js using webpack (v3) with default settings, it results in a rather large package size of 455kb.

Using the great plugin Webpack Bundle Analyzer helps to spot that the large package size is a result of including all different locales:

Before

To reduce the bundle size, we configure webpack using webpack.ContextReplacementPlugin to only bundle locales used within the application, in following case DE & EN locales.

We add following snippet to the webpack.config.js file:

new webpack.ContextReplacementPlugin(
/moment[\/\\]locale$/,
/de|en/
)

After

The result is a reduced package size of 125kb.

Related Posts

Scroll Bottom with React

Scrolling to bottom with React using the Lifecycle Methods and Dom Reference

Javascript condition & 0 value

How to prevent headaches with 0 values and Javascript conditions