How To Enable ES6 Imports in Node.JS

13 Nov · by Tim Kamanin · 2 min read

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-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 starter.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 'env' (aka ES6) preset.
require('babel-register')({
    presets: [ '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.

Comments

Required for comment verification