By default Moment.js is bundled with a plethora of locales which might not all be relavent to you or your users. In this article I want to look at how much of a size reduction we can use by stripping out unwanted locales using webpack via Laravel-Mix.
First lets get a benchmark filesize by seeing what the minified and unminfied/optimised versions of the default laravel code base look like:
composer create-project --prefer-dist laravel/laravel moment-test
The console should show the following:
DONE Compiled successfully in 7577ms 11:41:37 AM
So 1.38mb for our unminified code.
and 332kb for minified/optimised.
Now lets add moment.js to our project and re-run the same commands above to see their minified and unminified sizes.
yarn add -D moment
After the last command has finished you should see something like:
DONE Compiled successfully in 8771ms 11:33:21 AM
Asset Size Chunks Chunk Names
/js/app.js 1.92 MB 0 [emitted] [big] /js/app
/css/app.css 195 kB 0, 0 [emitted] /js/app, /js/app
✨ Done in 12.92s.
Our unminifed JS is a whopping 1.92mb.
Lets see what its like after minifiying and optimising that same code:
Much better at 562kb but still thats pretty huge given that we actually haven’t written code for our application yet!
By default Moment.js comes with (at the time of writing) 123 locales. A lot of the work I do is entirely written for British consumers and so there are 122 additional locales being bundled that the consumers of my work will never need. I looked into stripping the additional locales out and ended up with the following code in my projects
yarn dev and
yarn prod commands resulted in some substancial file size savings which can be seen in the table below:
|Laravel with Moment.js||1.92MB||562kB|
|Laravel with Moment.js and locales stripped||1.53MB||385kB|
You can obviouly replace the string en-gb with a pipe delimted list of locales from the
node_modules/moment/locale/ folder, for example:
// A regular expression matching files that should be included
Hopefully this should help you feel better about the amount of data we’re pushing down the wire when using a library as useful as Moment.js.
If you have any further tips for optimising Moment.js or any other library I’d love to hear about them!