来自 Python 背景和 Node.js 的新手,我发现使用 Node.js REPL 交互式地尝试代码非常困难。我遇到的一个关键问题是 imports
:
ES6 样式导入在 Node.js REPL 上不起作用,我必须通过 require
使用 CommonJS 样式导入。示例:我无法在 Node 提示符下编写 import rxjs
,必须使用 require('rxjs')
。这使得将粘贴脚本复制到 Node REPL 以快速测试它们变得更加困难,我必须首先将所有 ES6 样式导入转换为 require 导入,这感觉违反直觉。
有没有什么简单的方法可以使用从 Node.js REPL 导入的 ES6 样式?
喜欢:
$ node
> import 'rxjs';
> import {map} from 'rxjs/operator/map';
我什至尝试过似乎不支持模块导入的 babel-node
。
最佳答案
恐怕答案是否,或者至少还没有。我们知道将来会支持它,但是 ES2015 import
和 export
不会作为 CommonJS require
的就地替换和 module.exports
。这仅仅是因为它们的工作方式不同。您可以在 this Node.js blog post 中找到更多信息和 this SO question .特别是,已经可以在 Node.js 中运行和导入标准模块,标记为 --experimental-modules
(相关 2ality blog post)。但是,此功能仍然无法在 REPL 中使用。
您使用 babel-node
(现在称为 babel-cli
)的想法还不错:babel
实现了一个可互操作的 require
函数,这是一种 shim,可以检索为任一类型系统设计的模块。不幸的是,official website声称在 REPL 中不支持此功能:
ES6-style module-loading may not function as expected
Due to technical limitations ES6-style module-loading is not fully supported in a babel-node REPL.
尽管如此,这个问题不适用于生产代码,它不应该依赖于 REPL。除了使用 REPL,您可以考虑在包含 babel-cli
的基本项目中编写一个脚本,并创建一个用于运行转译版本的脚本:
{
"name": "my-test-chamber",
"private": true,
"scripts": {
"build": "babel src/main.js -o lib/main.js",
"start": "npm run build && node lib/main.js"
},
"dev-dependencies": {
"babel-cli": "^6.0.0"
}
}
关于javascript - Node.js REPL 中的 ES6 样式导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530880/