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.
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.
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.
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"type": "module", "scripts": {
"start": "node app.js"
}
}