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

Solution 1:

In order to use the import syntax (ESModules), you need to set the following to your package.json at the top level:

{
    // ...
    {"type": "module" }
}

If you are using a version of Node earlier than 13, you need to use the --experimental-modules flag when you run the program

node --experimental-modules program.js

and add {"type": "module" } in package.json

Hope it helps !

Solution 2:

Use commonjs syntax instead of es module syntax:

module.exports.func = function (){
    console.log("Hello World");
}

and

const myMod = require("./mod")
myMod.func()

Otherwise, if you want to use es modules you have to do as the answer by Achraf Ghellach suggests

Solution 3:

I recently encountered this problem. This solution is similar to the top rated answer but with some ways I found worked for me.

In the same directory as your modules create a package.json file and add "type":"module". Then use import {func} from "./myscript.js";. The import style works when run using node.

Solution 4:

In addition to the answers above, note by default(if the "type" is omitted) the "type" is "commonjs". So, you have explicitly specify the type when it's "module". You cannot use an import statement outside a module.