BRIEFS logo BRIEFS

Getting a Native ESM module imported into a CommonJS module

03/13/2021 , 2m, 59s

Hey friends So today. I just want to mention something that I've been working on for the last couple days. So if you didn't know node version 10 is the last version of node that so does not support native ECMAScript modules without a flag. So you can use ECMAScript modules with node version 10, but you need to pass it a flag version 12 and above I'll do not require a flag they just support a native ESM out of the box.

And what's exciting about this is it means that package authors can start using native ES module.'s and and we can consume them as native modules and we don't have to compile down or compile away those ES modules. This is a good thing but it also comes with a fair number of complications.

For one thing we're not there are interesting semantics with the way that ESM works native ESM. For example, you cannot use require for a native ES module. So, you can't just require a library or another module that you've written. You.Have to use an import statement. Now, you're probably working in if you're working in a node application, you're probably working in one that is not using native ESM if you if you are using native that's awesome good for you, but most of us probably aren't.

So we're either compiling our import statements to require or we're requiring writing require ourselves. And so if you want to start using packages that are built with native ESM, then you're going to need to do things a little bit differently. So you.Can't use an import statement in a common JS module.

So a non-ESM module. And so the only way to get a ESM module into your common JS module is by using a dynamic import statement, which looks like a function when you call import. It's an asynchronous operation, so you need to use asynchle weight. Luckily for us node version, or yeah recently at some point.

I think version 14, we know have support for root or or module async await. Unfortunately,That only works in native ESM modules So if you want to use a if you're writing a common JS module and you want to import a ESM module the only way to do it is to use a dynamic import and you have to it's asynch weight and so or or promise I guess.

And so, you have to write an async function to be able to import anything from ESM. There's I'm going to need to like write a blog post about this and stuff because there are a couple of interesting things here. It's going to be a little bit painful, but I think in the end we're all going to be much.

Better off just going full native ESM. I hope that's interesting. Bye.