SyntaxError: 不能在模块外使用 import 语句

当试图从另一个 javascript 文件导入时,我得到了这个错误 SyntaxError: Cannot use import statement outside a module。这是我第一次尝试这样的东西。主文件是 main.js,模块文件是 mod.js

Js:

import * as myModule from "mod";
myModule.func();

Mod.js:

export function func(){
console.log("Hello World");
}

我该怎么补救,谢谢

150717 次浏览

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

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.

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.

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

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

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.

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