如何启用node.js_如何在Node.js中启用ES模块

如何启用node.js

Many tutorials now use the import XXX from 'XXX' (ES Modules) syntax instead of const XXX = require('XXX') (CommonJS) syntax.

现在,许多教程使用import XXX from 'XXX' ( ES模块 )语法import XXX from 'XXX'而不是使用const XXX = require('XXX') ( CommonJS )语法。

If you add that to your Node.js app, it won’t work. You’ll get an error like this:

如果将其添加到Node.js应用程序,它将无法正常工作。 您将收到如下错误:

unexpected identifier error

unexpected identifier..

unexpected identifier..

One of the solutions to this is to use Babel. If you already have a Babel setup for your project, this should already be working for you.

解决此问题的方法之一就是使用Babel 。 如果您已经为您的项目准备了Babel设置,那么它应该已经为您工作。

But you shouldn’t need Babel any more now because Node has experimental support for ES Modules, and since it’s experimental, to enable it you must do 3 things.

但是,您现在不再需要Babel,因为Node具有对ES模块的实验性支持,并且由于它是实验性的,要使其具备功能,您必须做三件事。

First, install the latest version of Node.js. It has the latest and greatest features.

首先,安装最新版本的Node.js。 它具有最新和最强大的功能。

Second, add the "type": "module" line in your package.json file.

其次,在package.json文件中添加"type": "module"行。

Third, use the --experimental-modules flag when invoking nodejs:

第三,在调用nodejs时使用--experimental-modules标志:

node --experimental-modules app.js

You should be good to go!

你应该很好走!

An alternative is to avoid adding the "type": "module" line in your package.json file and instead rename your app.js file (or whatever) to app.mjs.

一种替代方法是避免在package.json文件中添加"type": "module"行,而将您的app.js文件(或其他名称)重命名为app.mjs

Note that now the require() syntax will stop working.

请注意,现在require()语法将停止工作。

For older Node.js versions that might not support this flag, I recommend checking out the esm npm module.

对于可能不支持此标志的旧版Node.js,建议您检查esm npm模块

翻译自: https://flaviocopes.com/how-to-enable-es-modules-nodejs/

如何启用node.js

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值