I am getting this error SyntaxError: Cannot use import statement outside a module when trying to import from another javascript file. This is the first time I'm trying something like this. The main file is main.js and the module file is mod.js.
main.js:
import * as myModule from "mod";
myModule.func();
mod.js:
export function func(){
console.log("Hello World");
}
How can I fix this? Thanks
In order to use the import syntax (ESModules), you need to add the following to your package.json at the top level:
{
// ...
"type": "module"
}
If you are using a version of Node earlier than 13, you additionally need to use the --experimental-modules flag when you run the program:
node --experimental-modules program.js
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.