Node.js:语法错误:不能在模块外使用导入语句 [英] Node.js: SyntaxError: Cannot use import statement outside a module
问题描述
我收到此错误 SyntaxError:无法在模块外使用 import 语句
尝试从另一个 javascript 文件导入时.这是我第一次尝试这样的事情.主文件为main.js
,模块文件为mod.js
.
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
推荐答案
为了使用导入语法(ESModules),你需要在你的 package.json 的顶层设置以下内容:
In order to use the import syntax (ESModules), you need to set the following to your package.json at the top level:
{
// ...
{"type": "module" }
}
如果你使用的 Node 版本早于 13,你需要在运行程序时使用 --experimental-modules 标志
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
并添加 {"type": "module";} 在 package.json 中
and add {"type": "module" } in package.json
希望能帮到你!
这篇关于Node.js:语法错误:不能在模块外使用导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!