How to convert your library to ES6

Calvin Metcalf
Jul 20, 2017 · 2 min read

Some quick do’s and don’ts (mainly don’ts) about converting your library to ES6 modules.

Quick note: This is about how to convert your library to ES6 modules, it is not about how to right a library from scratch in ES6, the main focus is on how to avoid accidentally introduce backwards compatibility.

Don’t Import *

When converting a module you should avoid doing any import * as foo from ./bar.js,this is the most important thing. When you import a module like this you get none of the benifits of ES6 modules while getting some significant drawbacks.
Quick whats the difference between way1 and way2 in b.js

The answer is that way2 is a normal JS object with 2 methods, while way1 is an exotic module object that is not extendable and is frozen.

What should you do instead

If its part of the public facing API (aka you are taking what you import and assigning it to something) make an object and export it instead.
If you’re using it internally (like it’s a utils module or something), just import the keys you need, even if its a lot of keys, if its not all of them you should probably use named imports.

Socratic Documentation

But doesn’t using export default on an object defeat the purpose of ES6 modules and prevent dead code elimination?

Yes but so does import * as foo

Is this actually a problem?

yes it is

But my library doesn’t rely on people extending any of the objects with new methods

You’re probably okay then just be aware it’s a difference

here’s a picture of my dog so that medium is will show a preview image.

)

Calvin Metcalf

Written by

Cartographer, Programmer, Cat Aficionado, Dog Owner

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade