Home > Designing, Others > Import Non-ESM libraries in ES Modules, with Client-Side Vanilla JS

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

September 7th, 2020 Leave a comment Go to comments

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:

CodePen Embed Fallback

Check out the article for another clever little trick.

Direct Link to ArticlePermalink


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.

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.