Derek Chan

When It's Worth Reinventing the Wheel

When it comes to common utility functions, many would not dare think about reinventing the wheel, especially in the JavaScript world. It can help save time and spare a developer extra unit tests (and much headache).

However, if you think about it, how much of the available functionality a library provides are you actually going to use? Are you going to cover all conditions the library accounts for? Is it really worth the extra unused code in your app bundle?

You're not thinking hard enough if you answered "everything" or "all of it."

From my experience, many app bundles tend to be very large in size because of unused code injected by dependencies. Even importing a single function from a library can still warrant the entire thing (or a substantially large portion thereof) being inserted into the bundle, especially when using bundlers such as Webpack.

So my solution? Reimplement them in the simplest way possible and refactor accordingly.

As an example, I refactored code dependent on Moment functions, most of them related to parsing and string formatting. Moment falls back to the native JavaScript way of parsing date strings. As for the string formatting, I didn't see a need to make an entire function to account for any format string, as many of the existing ones in the code pretty much only used the month, day, hour and minute portions.

An especially infamous example would be dealing with Underscore. Code I was once working with used only one function from the entire library, so I reimplemented it.

Ultimately, the choice is yours. The above examples are relatively simple. There are functions that definitely require rigorous testing to ensure correctness, and thus cannot be reimplemented. Nonetheless, if you are able to pull off the reimplementation, you will spare the app bundle a lot of code, and spare your users waiting time and space as well, even if your bundle is compressed.

Powered by Enigma CMS.

Login | Register

,