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

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

In this post we will give you information about How to resolve the SyntaxError: Unexpected token import Node.js. Hear we will give you detail about How to resolve the SyntaxError: Unexpected token import Node.jsAnd how to use it also give you demo for it if it is necessary.

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"  }}

Hope this code and post will helped you for implement How to resolve the SyntaxError: Unexpected token import Node.js. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US