29
votes

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

4
Which version of nodejs?gautam1168
@gautam1168 v12.16.2Serket

4 Answers

43
votes

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 !

13
votes

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

2
votes

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.

0
votes

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.