跳至主内容

@babel/node

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

babel-node 是一个命令行工具,其功能与 Node.js CLI 完全一致,但额外增加了在运行前使用 Babel 预设和插件编译代码的优势。

安装

npm install --save-dev @babel/core @babel/node
注意

不适用于生产环境

不应在生产环境中使用 babel-node。它过于臃肿,由于缓存存储在内存中导致内存占用过高,且启动性能必然受损——整个应用需要即时编译。

查看 Babel 实现的 Node.js 服务器示例,了解生产部署中如何使用 Babel。

ES6 风格模块加载可能异常

由于技术限制,babel-node REPL 中无法完整支持 ES6 风格的模块加载功能。

Babel 提供了第二个命令行工具,其功能与 Node.js CLI 完全相同,区别在于它会在运行前编译 ES6 代码。

启动 REPL(读取-求值-输出循环)交互环境。

备注

请在使用 npx babel-node 前先安装 @babel/node@babel/core,否则 npx 会安装过时的旧版 6.x babel-node

Shell
npx babel-node

若不希望预先安装 @babel/node@babel/core,可实时安装:

Shell
npx -p @babel/core -p @babel/node babel-node

执行代码片段。

Shell
npx babel-node -e "class Test { }"

编译并运行 test.js

Shell
npx babel-node test
提示

使用 rlwrap 获取带输入历史的 REPL

Shell
rlwrap npx babel-node

在某些平台(如 OSX)需额外参数才能使 rlwrap 正常工作:

Shell
NODE_NO_READLINE=1 rlwrap --always-readline npx babel-node

使用方式

Shell
babel-node [options] [ -e script | [--] script.js ] [arguments]

当用户脚本参数名与 node 选项冲突时,可在脚本名前添加双破折号消除歧义:

Shell
npx babel-node --inspect --presets @babel/preset-env -- script.js --inspect

选项

OptionDefaultDescription
-e, --eval [script]Evaluate script
-p, --printEvaluate script and print result
-i, --ignore [regex]node_modulesIgnore all files that match this regex when using the require hook. If both -i and -o are omitted, files outside the current working directory are also ignored.
-o, --only [regex]current working directoryOnly include (and exclude all other) files that match this regex when using the require hook. If both -i and -o are omitted, files outside the current working directory are also ignored.
-x, --extensions".js",".jsx",".es6",".es","cjs"List of extensions to hook into
--presets[]Comma-separated list of presets (a set of plugins) to load and use.
--plugins[]Comma-separated list of plugins to load and use.
--config-file [path][]Path to the babel config file to use. Defaults to working directory babel.config.json or babel.config.js. The following options in config files are not supported: ignore, only.
--env-name [name][]The name of the 'env' to use when loading configs and plugins. Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.