Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS
We’re living through a weird era where there are tons of JavaScript libraries that were meant to be used as 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("https://cdn.jsdelivr.net/gh/reworkcss/css@latest/lib/parse/index.js").then(_ => {
console.log(module.exports);
});
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 to Article — Permalink
The post Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.