Using import/export in node.js with esm
When I started using node 6 years ago I took a quick liking to module loading in node.
require() is pretty straightforward. You import with
require() and export with
2 years ago when I started using es6 import / export syntax on the client with webpack, it often became annoying to have to deal with 2 different module loaders in my code. We eventually started using babel on the server so we could use import/export syntax in
.es6 files for our app.
I never liked having a build step on the server, and I omit when possible.
Thankfully John-David Dalton (who created Lodash) made the esm module, which allows us to use es6 import/export syntax in node without a build step.
Adding ESM to your project
Esm is a simple npm module.
First we’ll run
$ npm install --save esm to install the module.
Then we’ll replace our entry file with this one:
In this case we’ve move our app code to
main.js which can now contain import/exports! 🎉 ✨
esmloader bridges the ESM of today to the ESM of tomorrow. — https://github.com/standard-things/esm
So good. It’s prod ready, fast, and has zero deps.