Node.js: SyntaxError: Cannot use import statement outside a module
In order to use the import syntax (ESModules), you need to set the following to your package.json:
{"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 !
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
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.