162

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

3

11 Answers 11

206

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
Sign up to request clarification or add additional context in comments.

3 Comments

not working for me
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.
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

4 Comments

Assuming ./mod is a file named mod.js containing part 1 of your answer, I still get ReferenceError: module is not defined
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.png
unfortunately I'm using pretty old version... 12 :(
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.
16

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",
   ....
}

2 Comments

Where do I put the package.json if it's a module installed with npm?
in the root directory of your project.
5

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

2 Comments

I'm having the same issue. I don't want to change the file extension to .mjs. I'm wondering if there's a command line option.
This solution definitely is what I needed, for me it's just a post-build.js script that I run inside package.json and I for sure did not want to make my full project a module. Apparently with node 23 it was not an issue to import a module in my external script but with node 20 it was. To change the script extension from .js to .mjs fixed OP error.
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.

Comments

2

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.

1 Comment

Great tip. You know, I hear "const" rather than "let" seems to be the way to go these days.
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.

Comments

1

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"
  }
}

Comments

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".

Comments

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.

2 Comments

As of Node 13 there is no need to use --experimental-modules flag, see nodejs.org/en/blog/release/v14.0.0
Is there a flag that can force node to look at a .ts file as a module? I tried node--experimental-modules test.ts and it failed. What seemed to work is if I change the file extension to .mjs. However, I'd rather avoid that because it causes other issues. I don't want to change my package.json settings either.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.