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

11

145

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

Swound answered 20/6, 2020 at 16:56 Comment(3)
Which version of nodejs?Bucko
Does this answer your question? SyntaxError: Cannot use import statement outside a moduleStripy
@Bucko v12.16.2Swound
U
183

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
Unexceptional answered 20/6, 2020 at 17:2 Comment(6)
Note - Add a comma at the end of codpiece providedJewfish
not working for meSilvanus
https://mcmap.net/q/161076/-unknown-file-extension-quot-ts-quot-error-appears-when-trying-to-run-a-ts-node-script was helpful.Silvanus
Actually, for NodeJS to interpret a script as a module, you only need to have a package.json file with just { "type": "module" } into the closest ancestor directory, including the same directory as your script.Laryngoscope
@EklavyaChandra are you sure you meant codpiece? en.wikipedia.org/wiki/CodpieceRento
@Rento I think I mean to say code, autocorrect maybe ☕Jewfish
B
35

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

Bucko answered 20/6, 2020 at 17:7 Comment(4)
Assuming ./mod is a file named mod.js containing part 1 of your answer, I still get ReferenceError: module is not definedGriefstricken
Assuming you have nodejs 16 or higher it should work. Are you maybe using the keyword module during require as a variable? Check this screenshot: pasteboard.co/D41OnBGMT81z.pngBucko
unfortunately I'm using pretty old version... 12 :(Griefstricken
I don't know if this will help on that version, but you may try after adding the extension: var mymod = require("./mod.js"). This require style is pretty old so I would have expected it to work on node 12 as well.Bucko
T
10

For browser(front end): add type = "module" inside your script tag i.e

<script src="main.js" type="module"></script>

For nodejs: add "type": "module", in your package.json file

{
  "name": "",
  "version": "",
  "description": "",
  "main": "",
  "type": "module",
   ....
}
Tandy answered 16/5, 2022 at 4:18 Comment(0)
C
4

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.

Corena answered 10/6, 2021 at 9:17 Comment(0)
M
2

I was running into this issue with Node 18 with a single file src/index.js that uses import statements, here's the error message I got:

(node:13859) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node-18 --trace-warnings ...` to show where the warning was created)
[...redacted...]src/index.js:5
import { createServer } from 'node:http'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1178:20)
    at Module._compile (node:internal/modules/cjs/loader:1220:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
    at node:internal/main/run_main_module:23:47

The only things I had to do to resolve this was rename my src/index.js to src/index.mjs and start it with the command node src/index.mjs (node src finds index.js but not index.mjs). Happy day:

$ node src/index.mjs 
Server is running on http://localhost:8080
Multiangular answered 24/10, 2023 at 22:33 Comment(0)
U
1

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.

Uprise answered 19/4, 2021 at 21:35 Comment(0)
T
1

If you are in the browser (instead of a Node environment), make sure you specify the type="module" attribute in your script tag. If you want to use Babel, then it must be type="text/babel" data-plugins="transform-es2015-modules-umd" data-type="module".

Triumvir answered 7/4, 2022 at 21:56 Comment(0)
D
1

I got the same issue but in another module (python-shell). I replaced the code as follows:

import {PythonShell} from 'python-shell'; (original code)
let {PythonShell} = require('python-shell')

That solved the issue.

Doi answered 8/4, 2022 at 21:12 Comment(0)
F
1

You can run a js script by node --experimental-modules without changing package.json as below:

node --experimental-modules ./path/to/your/js/script.mjs

Note that you need change your script ext to .mjs, otherwise a SyntaxError: Cannot use import statement outside a module error will occur.

Flatling answered 20/10, 2023 at 4:44 Comment(1)
As of Node 13 there is no need to use --experimental-modules flag, see nodejs.org/en/blog/release/v14.0.0Multiangular
D
0

I had this issue trying to run mocha tests with typescript. This isn't directly related to the answer but may help some.

This article is quite interesting. He's using a trick involving cross-env, that allows him to run tests as commonjs module type. That worked for me.

// package.json
{
  ...
  "scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' mocha -r ts-node/register -r src/**/*.spec.ts"
  }
}
Dinger answered 10/2, 2022 at 14:50 Comment(0)
O
0

In my case, I had my typescript project and I wanted to run a ts file, while running node file.ts Turns out I was using the wrong command to run the file.

Command to use: npx tsc file.ts

Followed by: node file.js

Running the first command will compile the ts and generate a new file with same name but ts extension.

Outthink answered 5/1 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.