Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS

Avatar of Chris Coyier
Chris Coyier on

Find and fix web accessibility issues with ease using axe DevTools Pro. Try for free!

We’re living through a weird era where there are tons of JavaScript libraries that were meant to be used as <script> tags that expose available globals. AND there are tons of JavaScript libraries that are meant to be used through module loaders. AND there are tons of JavaScript libraries that assume you will use them via npm. AND there are tons of libraries built for ES6 imports. If you write a JavaScript library and are shooting for maximum usage, you’d make it work in all those ways, even though that’s obnoxious legwork.

I love Lea’s ideas here on taking libraries that were never really meant to be ES6 import-ed, but doing it anyway.

For example:

window.module = {};
import("[email protected]/lib/parse/index.js").then(_ => {

And a function if you needed to be safer about that, like a little abstraction:

Check out the article for another clever little trick.

Direct Link →