by Sai gowtham

How to resolve the SyntaxError: Unexpected token import Node.js

In this tutorial, we are going to learn about how to resolve the unexpected token import error in Node.js.

When we use es6 modules import/export statements in Node.js. It gives a following error in the terminal because node is currently not supporting the es6 modules by default.

app.js
import express from "express";

const app = express();

app.get("/hello", (req,res)=>{
   res.send("hello")
})

app.listen(3000, ()=> console.log("server is running"));

Output:

import express from "express";
^^^^^^

SyntaxError: SyntaxError: Unexpected token import
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11

To fix this error, we can use the commonjs modules require() function and module.exports instead of es6 modules.

app.js
const express =  require("express");

const app = express();

app.get("/hello", (req,res)=>{
   res.send("hello")
})

app.listen(3000, ()=> console.log("server is running"));

Or you can use the es6 modules by adding a --experimental-modules flag to the node command and set "type":"module" to the package.json file.

node --experimental-modules app.js

This above command can be used in node versions 8, 9, 10, 11, 12.

For node version >=13 you can use the es6 modules by setting a "type":"module" to the package.json file. There is no need of --experimental-modules flag in node command.

package.json
{
  "name": "my-app",
  "version": "1.0.0",
  "description": "",
  "type": "module",  "scripts": {
    "start": "node app.js"
  }
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course