10

I'm using the latest version of Node.js that is v8.4.0. However, in the import and export statements, I'm getting errors:

import express from 'express';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:598:3

What Node.js version should I install in order to work these ES6 codes?

  • OS - Ubuntu 17.04
  • node -v: v8.4.0
  • npm -v: 5.3.0
Sayed Mohd Ali
  • 2,004
  • 3
  • 8
  • 25
Gijo Varghese
  • 8,506
  • 17
  • 61
  • 104

2 Answers2

26

One way that I have worked around this issue...

Install babel stuff for the project:

$ npm install babel-register babel-preset-es2015 --save-dev

Create an index.js file that is the main entry point into the app:

// index.js 
// by requiring `babel/register`, all of our successive `require`s will be Babel'd
require('babel-register')({
   presets: [ 'es2015' ]
});

require('./server');

Then, create a file called server.js that will have your normal index code:

// server.js
import express from 'express';

var app = express()

app.get('/', (req, res) => res.send('Hello World!'))

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

And run:

$ node index.js 
Chris Livdahl
  • 4,314
  • 2
  • 34
  • 31
  • 1
    From https://babeljs.io/env/: "instead of continuing yearly presets, the team recommends using babel-preset-env". Therefore the 'es2015' preset in your code should probably be updated to 'env' (babel-preset-env) – Giovanni P. May 04 '18 at 21:09
  • import with directory name showing error. unexpected token for __ import pdf from __dirname + '/../../../index.js'; – Sayed Mohd Ali Nov 27 '18 at 07:40
-1

const express = require('express'); is the right syntax as some es6 features ie import express from express is currently not available with node!