Node.js:SyntaxError:无法在模块外部使用导入语句 [英] Node.js: SyntaxError: Cannot use import statement outside a module

查看:70
本文介绍了Node.js:SyntaxError:无法在模块外部使用导入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误 SyntaxError:尝试从另一个JavaScript文件导入时,无法在模块外部使用import语句.这是我第一次尝试这样的事情.主文件是 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");
}

我该如何解决?谢谢

推荐答案

要使用导入语法(ESModules),您需要在package.json中设置以下内容:

In order to use the import syntax (ESModules), you need to set the following to your package.json:

{"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:SyntaxError:无法在模块外部使用导入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆