Search This Blog

2024/03/19

Node.js :SyntaxError(Cannot use import statement outside a module)

Suppose you have a normal node.js file index.js as follows

index.js
import "core-js";
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];

const result = inventory.group(item=>{
return item.type
})
console.log(result)

const result2 = inventory.groupByToMap(item=>{
return item.type == "meat"?"Non-Veg":"Veg"
})
console.log(result2)

Explanation:
Here we are using import not commonly used in old style coding with common.js.
when you run the file as node index.js most probabally yoy will get error as
follows:

SyntaxError: Cannot use import statement outside a module

Solution:
You can resolve it by adding type as module in packgage.json as follows:
{
"name": "phenix",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"type": "module",
"license": "ISC",
"dependencies": {
"core-js": "^3.36.1"
}
}

No comments:

Post a Comment