ChatGPT解决这个技术问题 Extra ChatGPT

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

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

Which version of nodejs?
@gautam1168 v12.16.2

T
Tim Trayler

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!


Note - Add a comma at the end of codpiece provided
not working for me
g
gautam1168

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


r
ro_alli

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.


L
Lekia

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.


j
johnnyBoy

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

S
Simone

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


k
kob003

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


S
Snowcat

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.