当前位置: 首页 > 文档资料 > Babel 中文文档 >

@babel/cli

优质
小牛编辑
120浏览
2023-12-01

Babel 自带了一个内置的 CLI 命令行工具,可通过命令行编译文件。

此外,各种可直接调用脚本都存放在 @babel/cli/bin 中。一个可通过 shell 执行的实用脚本 - babel-external-helpers.js,以及 Babel cli 主脚本 babel.js

安装

虽然你 可以 在你的计算机上将 Babel CLI 安装到全局环境中,但是更好的方式是 将 Babel CLI 安装到每个项目的 本地 目录下。

这主要有两个原因:

  1. 同一台计算机上的不同项目可能依赖不同版本的 Babel ,并且你可以针对项目单独升级 Babel 的版本。
  2. 没有对你所正在工作的环境的隐性依赖 能够让你的项目更易于迁移和设置。

我们可以通过运行以下命令在本地安装 Babel CLI :

npm install --save-dev @babel/core @babel/cli

注意: 如果不存在 package.json 文件,请在安装之前创建一个。这将确保能够使用 npx 命令。

安装完成后,你的 package.json 文件应当包括如下内容:

{
  "devDependencies": {
+   "@babel/cli": "^7.0.0",
+   "@babel/core": "^7.0.0"
  }
}

用法

babel script.js

注意: 以下这些操作命令使用了 npx 来运行安装到本地的可执行文件。 你可以将这些命令放到 npm run script 配置中,或者使用相对路径,即 ./node_modules/.bin/babel

编译文件

编译 script.js 文件并 输出到标准输出设备(stdout)

npx babel script.js
# output...

如果你希望 输出到文件 ,可以使用 --out-file-o 参数。

npx babel script.js --out-file script-compiled.js

要在 每次文件修改后 编译该文件,请使用 --watch-w 参数:

npx babel script.js --watch --out-file script-compiled.js

编译并输出源码映射表(Source Maps)

如果你希望输出 源码映射表(source map)文件 ,你可以使用 --source-maps-s 参数。了解更多有关源码映射表(source map)的信息

npx babel script.js --out-file script-compiled.js --source-maps

或者,如果你希望使用 内联源码映射表(inline source maps),请使用 --source-maps inline 参数。

npx babel script.js --out-file script-compiled.js --source-maps inline

编译整个目录

编译整个 src 目录下的文件并输出到 lib 目录,输出目录可以通过 --out-dir-d 指定。这不会覆盖 lib 目录下的任何其他文件或目录。

npx babel src --out-dir lib

编译整个 src 目录下的文件并将输出合并为一个文件。

npx babel src --out-file script-compiled.js

忽略某些文件

忽略规范和测试文件

npx babel src --out-dir lib --ignore "src/**/*.spec.js","src/**/*.test.js"

拷贝文件

拷贝不需要编译的文件

npx babel src --out-dir lib --copy-files

通过管道输入文件

通过 stdin 和管道(pipe)将文件内容传递给 babel 命令,并将编译结果输出到 script-compiled.js 文件

npx babel --out-file script-compiled.js < script.js

使用插件

通过 --plugins 参数指定要在编译过程中所使用的插件。

npx babel script.js --out-file script-compiled.js --plugins=@babel/proposal-class-properties,@babel/transform-modules-amd

使用 Preset

通过 --presets 参数指定要在编译过程中所使用的 preset。

npx babel script.js --out-file script-compiled.js --presets=@babel/preset-env,@babel/flow

忽略 .babelrc 文件

忽略项目中的 .babelrc 配置文件,并通过命令行参数执行定制化的构建流程

npx babel --no-babelrc script.js --out-file script-compiled.js --presets=es2015,react

高级用法

还有很多参数可以使用,请参阅 optionsbabel --help 和其他章节以获取更多信息。