【问题标题】:Why not using import in Nodejs but arrow functions为什么不在 Nodejs 中使用 import 而使用箭头函数
【发布时间】:2019-10-15 05:00:21
【问题描述】:

我是 nodejs 的新手。 我看到我们正在使用

const http = require('http') 

而不是 import 。我发现这是因为 nodejs 比 es6 更老

why node uses require not import?

但是,我可以使用箭头函数。这是es6。怎么可能?

谢谢

【问题讨论】:

标签: node.js ecmascript-6


【解决方案1】:

终于发生了:在 ES6 中引入 import 关键字将近 4 年后,Node.js 引入了对 ES6 导入和导出的实验性支持。在 Node.js 12 中,如果您同时执行以下两项,则可以在项目中使用导入和导出。

1) 在运行 Node.js 时添加 --experimental-modules 标志

2) 使用 .mjs 扩展名或在 package.json 中设置 "type": "module"

这个 package.json 非常重要。 type: "module" 属性告诉 Node.js 将 .js 文件视为 ESM 模块。换句话说,{"type":"module"} 告诉 Node.js 期待 .js 文件中的 import 和 export 语句。

你可以像这样运行文件 node --experimental-modules index.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2019-07-24
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多