JavaScriptJavaScript

How To Enable ECMAScript 6 Imports in Node.JS

May 20, 2019 · Updated: Aug 28, 2020 · by Tim Kamanin

Back in 2017, I wrote a tutorial about the same topic. Today, I'm updating it with a better solution.

Today, in 2019, Node.js still doesn't support ES6 imports. Well, you could experimentally use them in .mjs files, but it's more trouble than it's worth.

So we're still in need of a third-party solution if we want le to use import SuperPower from 'source-of-super-powers' syntax in our node code.

For example, if we try to write a simple express.js code like this:

// file server.js
import express from 'express'
const app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

And then, we run as node server.js, we'll get an error SyntaxError: Unexpected token import. Which in node.js words means Dude, I don't understand what you're trying to do here!.

The solution

Luckily, we're in node.js land where any problem can be solved with a hammer package.

And there's a package for our case too! It's called esm, the brilliantly simple, babel-less, bundle-less JavaScript module loader.

  1. Install esm in your project: npm install --save esm

  2. Run your code with esm: node -r esm server.js

And it should work without any code modifications. Pure magic!

The best thing is that contrary to previous babel-based solutions, this approach is production-friendly.

What if I use nodemon?

You can provide nodemon with -r esm parameter too:

nodemon -r esm server.js

As simple as it is :)

What if I can't/don't like to use '-r esm' parameter?

You can omit -r esm parameter when you run a node script. Instead, you need to create an entrypoint file that loads esm for before application code.

This file could look like:

// file start.js
require = require("esm")(module /*, options*/);
module.exports = require("./server.js");

Note we're importing our ./server.js here.

Now run the app as node start.js and it should work as flawlessly as node -r esm server.js. You choose which approach is more suitable.

Well, that's all. Now you can enjoy the last missing piece of the modern JavaScript in Node.js.

You're welcome... If you find this post helpful, please don't hesitate to share it as wildly as possible. I appreciate this!

P.S. Let's connect! Follow me on twitter @timonweb, so we could be in touch. I regularly share tips and interesting dev links there. See you.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓