Nov 13, 2017 · Updated: Jan 04, 2021 · by Tim Kamanin
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.
npm install @babel/core @babel/register @babel/preset-env --save-dev
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:
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.
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: