Earlier this year I blogged about reducing the file size of moment.js by stripping out additional locales. Whilst stripping the locales made a good saving in file size, really all I was using it for was to format dates within my user interfaces. So I set out on finding a lightweight alternative to do just that…
In my quest to reduce my bundle size I came across a few libraries and the easiest one I found to swap in was one called dayjs. It weighed in at 2kB and had the same (well very similar) API to that of moment.js.
Implementing it was easy - first add it to your
yarn add -D dayjs
With the library installed I set out to search for all of the references to moment within my project:
grep -i -r "moment" resources/js/
And then replaced the relevant imports from
dayjs and the method calls from
I did have to update a couple of the formatters as they weren’t exactly the same as moment.js’s but my test suite picked those errors up.
Following a production build I was able to compare the bundle sizes between
moment.js with locales remove and
dayjs in the project I was working on:
|Media-manager with moment.js||468kB|
|Media-manager with moment.js and locales stripped||281kB|
|Media-manager with dayjs||237kB|
So from using moment.js without any optimisation there a pretty huge file size saving of nearly 50%! After optimising moment by stripping out excess locales we’re still seeing a 44kB file size saving giving us an additional 15% saving on this particular bundle.
As well as giving a smaller bundle there was no longer any need to have additional configuration within my
Don’t forget to remove
momentjs from your
packages.json file and run
yarn to rebuild the lockfile.