node直接运行es6代码

默认情况下,Node.js运行JavaScript代码使用CommonJS。要直接运行ES6代码,需根据Node.js版本采取不同方法。对于低于13.2.0的版本,需在package.json中设置"type": "module",并使用`node --experimental-modules src/index.js`执行。而高于13.2.0的版本,只需添加"type": "module"即可。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

默认安装node之后,在运行javascript代码时使用的是commonjs方式,比如如下代码

import chalk from 'chalk'

console.log(chalk.red('helllo'));

直接运行会出错:

D:\studyTS\StudySnippet>node ownSnippet.js
(node:27268) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\studyTS\StudySnippet\ownSnippet.js:2
import chalk from 'chalk'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

解决办法和你node.js版本有关,如果是低于13.2.0,需要两步:

  • 在package.json中添加属性:"type": "module"
  • 在执行命令中添加如下选项:node --experimental-modules src/index.js
{
  "type": "module",
  "scripts": {
    "start": "node --experimental-modules index.js"
  }
}

如果版本大于13.2.0, 那么只需要一步即可!即添加属性"type": "module",比如

{
  "devDependencies": {
    "chalk": "^4.1.1"
  },
  "type": "module"
}

爱玩的安哥 倾心发布,让生活多一点儿乐趣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱玩的安哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值