Fix ’Cannot use import statement outside module error’ in Node.js

Many of you must have encountered the syntax error: Cannot use import statement outside a module, in Node.js. Mostly this error pops up when trying to import from another javascript file. If it's your first time using Node.js you might get confused about how to fix it. Let us see some examples. 

Main.js 
import * as myModule from "mod";
myModule.func();

Mod.js
export function func(){
    console.log("Hello World");
}

In this example to use import syntax you have to set the following to your package.json.

{"type": "module" }

If your Node.js version is below 13 use --experimental-modules flag when you run your program.

node --experimental-modules program.js

Then add {“”type”:”module”} in package.json. This will solve your problem.