Choosing Appropriate Libraries
Learn about the different factors that we need to consider when selecting libraries for our applications.
In modern web development, it’s very easy to find libraries for many different things. Do we need a nice-looking, custom select component with accessibility support? Or maybe a toggle switch? Head to npm, and there will be a package for that. When asked for the most well-known date manipulation library for JavaScript, many developers would probably answer that it’s moment.js.
The moment.js library
As of September 2020, the moment.js library is in maintenance mode and will not be receiving any more updates. However, we’ll still use it here as an example, as the comparison shows well what mistakes should be avoided. So, many developers would immediately choose to install moment.js if an application required data formatting. What’s the problem with that, we might ask? Well, the problem is that it’s overkill. The moment.js library is large, 71.2kb minified and gzipped. It offers many features for date manipulation, working with time zones, and so on. That said, we don’t need it just to display a date in a nice format. If that’s the only thing we need to do, we might want to use the Internationalization API. Below is an example of formatting a Date object to strings, 19 July 2020
for the UK and 7/19/2020
for the US.
const date = new Date(Date.UTC(2020, 6, 19, 4, 0, 0));const options_UK = {day: "numeric",month: "long",year: "numeric"};console.log(new Intl.DateTimeFormat("en-GB", options_UK).format(date));// 19 July 2020const options_US = {day: "numeric",month: "numeric",year: "numeric"};console.log(new Intl.DateTimeFormat("en-US", options_US).format(date)); // 7/19/2020
As we can see, there’s no need to add a library just to format a date. Unless, of course, we still have to support IE, because the Intl API isn’t supported by Internet Explorer. However, if we need a library because we have to perform calculations based on dates, time zones, and ...
Get hands-on with 1400+ tech skills courses.