How To Enable ES6 Imports in Node.JS

13 Nov ยท by Tim Kamanin ยท 2 min read

BIG UPDATE:

I wrote this post many moons ago. In JavaScript world, this means an eternity.

And there's a better solution which I talk about in my new tutorial here: How To Enable ECMAScript 6 Imports in Node.JS. Go there and read.

I'll leave the current post here for the sake of history.

******* WARNING, BELOW IS THE ARCHIVE POST ******

As of now, Node.js doesn't support ES6 imports yet. However, you can use them today with the help of Babel.

The following example is for the express.js server.

1. Install necessary packages

npm install @babel/core @babel/register @babel/preset-env --save-dev

2. Tweak your server.js

Here's an example server.js:

const express = require('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!'))

let's replace require(...) with ES6 Imports:

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!'))

If you go an run it now as node server.js, you'll get an error SyntaxError: Unexpected token import. It happens because we don't "babelify" our node.js code on the fly yet.

To do that we need to:

3. Add start.js file

This file will act as an entry-point for our node.js app and will contain babel registration code:

// Transpile all code following this line with babel and use '@babel/preset-env' (aka ES6) preset.
require("@babel/register")({
  presets: ["@babel/preset-env"]
});

// Import the rest of our application.
module.exports = require('./server.js')

And that's all, from now on, instead of running node server.js, start your app as node start.js and you will get a hassle-free ES6 Imports support in your node.js application.

Hope this helps.

******* WARNING, ABOVE IS THE ARCHIVE POST ******

Please read the updated version of this tutorial here.

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials