Skip to main content

使用指南

Babel 工具链中有很多工具试图让你轻松使用 Babel,无论你是 "终端用户" 还是构建 Babel 本身的集成。这将是对这些工具的快速介绍,你可以在文档的 "用法" 部分阅读更多关于它们的信息。

¥There are quite a few tools in the Babel toolchain that try to make it easy for you to use Babel whether you're an "end-user" or building an integration of Babel itself. This will be a quick introduction to those tools and you can read more about them in the "Usage" section of the docs.

如果你使用的是框架,那么配置 Babel 的工作可能会有所不同,或者实际上已经为你处理好了。请查看我们的 交互式设置指南

¥If you're using a framework, the work of configuring Babel might be different or actually already handled for you. Check out our interactive setup guide instead.

概述

¥Overview

本指南将向你展示如何将使用 ES2015+ 语法的 JavaScript 应用代码编译为可在当前浏览器中运行的代码。这将涉及转换新语法和填充缺失的功能。

¥This guide will show you how to compile your JavaScript application code that uses ES2015+ syntax into code that works in current browsers. That will involve both transforming new syntax and polyfilling missing features.

设置的整个过程包括:

¥The entire process to set this up involves:

  1. 运行这些命令来安装软件包:

    ¥Running these commands to install the packages:

    npm install --save-dev @babel/core @babel/cli @babel/preset-env
  2. 在项目的根目录中创建一个名为 babel.config.json(需要 v7.8.0 及更高版本)的配置文件,其中包含以下内容:

    ¥Creating a config file named babel.config.json (requires v7.8.0 and above) in the root of your project with this content:

    babel.config.json
    {
    "presets": [
    [
    "@babel/preset-env",
    {
    "targets": {
    "edge": "17",
    "firefox": "60",
    "chrome": "67",
    "safari": "11.1"
    },
    "useBuiltIns": "usage",
    "corejs": "3.6.5"
    }
    ]
    ]
    }

    上面的浏览器列表只是一个随意示例。你必须针对要支持的浏览器对其进行调整。有关更多 @babel/preset-env 选项,请参阅 此处

    ¥The browsers list above is just an arbitrary example. You will have to adapt it for the browsers you want to support. See here for more @babel/preset-env options.

或者 babel.config.js 如果你使用的是旧的 Babel 版本

¥Or babel.config.js if you are using an older Babel version

babel.config.js
const presets = [
[
"@babel/preset-env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
useBuiltIns: "usage",
corejs: "3.6.4",
},
],
];

module.exports = { presets };
  1. 运行此命令将 src 目录中的所有代码编译到 lib

    ¥And running this command to compile all your code from the src directory to lib:

    Shell
    ./node_modules/.bin/babel src --out-dir lib

    你可以使用 npm@5.2.0 附带的 npm 包运行器通过将 ./node_modules/.bin/babel 替换为 npx babel 来缩短该命令

    ¥You can use the npm package runner that comes with npm@5.2.0 to shorten that command by replacing ./node_modules/.bin/babel with npx babel

继续阅读以了解其工作原理的分步说明以及所使用的每种工具的介绍。

¥Read on for a step-by-step explanation of how this works and an introduction to each of the tools used.

CLI 的基本用法

¥Basic usage with CLI

你需要的所有 Babel 模块都作为单独的 npm 包发布,范围在 @babel 下(从版本 7 开始)。这种模块化设计允许使用各种工具,每种工具都针对特定用例而设计。在这里,我们将看看 @babel/core@babel/cli

¥All the Babel modules you'll need are published as separate npm packages scoped under @babel (since version 7). This modular design allows for various tools each designed for a specific use case. Here we'll look at @babel/core and @babel/cli.

核心库

¥Core Library

Babel 的核心功能位于 @babel/core 模块中。安装后:

¥The core functionality of Babel resides at the @babel/core module. After installing it:

npm install --save-dev @babel/core

你可以直接在你的 JavaScript 程序中 require 并像这样使用它:

¥you can require it directly in your JavaScript program and use it like this:

JavaScript
const babel = require("@babel/core");

babel.transformSync("code", optionsObject);

但是,作为终端用户,你可能希望安装其他工具作为 @babel/core 的接口并与你的开发过程很好地集成。即便如此,你可能仍想查看其文档页面以了解选项,其中大部分也可以从其他工具中设置。

¥As an end-user though, you'll probably want to install other tools that serve as an interface to @babel/core and integrate well with your development process. Even so, you might still want to check its documentation page to learn about the options, most of which can be set from the other tools as well.

命令行工具

¥CLI tool

@babel/cli 是一个允许你从终端使用 babel 的工具。这是安装命令和基本用法示例:

¥@babel/cli is a tool that allows you to use babel from the terminal. Here's the installation command and a basic usage example:

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

./node_modules/.bin/babel src --out-dir lib

这将解析 src 目录中的所有 JavaScript 文件,应用我们告诉它的任何转换,并将每个文件输出到 lib 目录。由于我们还没有告诉它应用任何转换,因此输出代码将与输入相同(不保留确切的代码样式)。我们可以通过将它们作为选项传递来指定我们想要的转换。

¥This will parse all the JavaScript files in the src directory, apply any transformations we have told it to, and output each file to the lib directory. Since we haven't told it to apply any transformations yet, the output code will be identical to the input (exact code styling is not preserved). We can specify what transformations we want by passing them as options.

我们使用了上面的 --out-dir 选项。你可以通过运行 --help 来查看 cli 工具接受的其余选项。但现在对我们来说最重要的是 --plugins--presets

¥We used the --out-dir option above. You can view the rest of the options accepted by the cli tool by running it with --help. But the most important to us right now are --plugins and --presets.

插件和预设

¥Plugins & Presets

转换以插件的形式出现,插件是小型 JavaScript 程序,指导 Babel 如何对代码进行转换。你甚至可以编写自己的插件来将你想要的任何转换应用于你的代码。要将 ES2015+ 语法转换为 ES5,我们可以依赖 @babel/plugin-transform-arrow-functions 等官方插件:

¥Transformations come in the form of plugins, which are small JavaScript programs that instruct Babel on how to carry out transformations to the code. You can even write your own plugins to apply any transformations you want to your code. To transform ES2015+ syntax into ES5 we can rely on official plugins like @babel/plugin-transform-arrow-functions:

npm install --save-dev @babel/plugin-transform-arrow-functions

./node_modules/.bin/babel src --out-dir lib --plugins=@babel/plugin-transform-arrow-functions

现在我们代码中的任何箭头函数都将转换为 ES5 兼容的函数表达式:

¥Now any arrow functions in our code will be transformed into ES5 compatible function expressions:

JavaScript
const fn = () => 1;

// converted to

var fn = function fn() {
return 1;
};

这是一个好的开始!但我们的代码中还有其他 ES2015+ 特性需要转换。我们可以使用 "预设",而不是一个一个地添加我们想要的所有插件,它只是一组预先确定的插件。

¥That's a good start! But we also have other ES2015+ features in our code that we want transformed. Instead of adding all the plugins we want one by one, we can use a "preset" which is just a pre-determined set of plugins.

就像使用插件一样,你也可以创建自己的预设来共享你需要的任何插件组合。对于我们这里的用例,有一个名为 env 的出色预设。

¥Just like with plugins, you can create your own presets too to share any combination of plugins you need. For our use case here, there's an excellent preset named env.

npm install --save-dev @babel/preset-env

./node_modules/.bin/babel src --out-dir lib --presets=@babel/env

无需任何配置,此预设将包含所有支持现代 JavaScript(ES2015、ES2016 等)的插件。但是预设也可以选择。让我们看看另一种传递选项的方式,而不是从终端传递 cli 和 preset 选项:配置文件。

¥Without any configuration, this preset will include all plugins to support modern JavaScript (ES2015, ES2016, etc.). But presets can take options too. Rather than passing both cli and preset options from the terminal, let's look at another way of passing options: configuration files.

配置

¥Configuration

根据你的需要,有几种不同的方法可以使用配置文件。请务必阅读我们关于如何 配置 Babel 的深入指南以获取更多信息。

¥There are a few different ways to use configuration files depending on your needs. Be sure to read our in-depth guide on how to configure Babel for more information.

现在,让我们创建一个名为 babel.config.json(需要 v7.8.0 及以上)的文件,其内容如下:

¥For now, let's create a file called babel.config.json (requires v7.8.0 and above) with the following content:

babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
}
}
]
]
}

现在 env 预设将只为我们的目标浏览器中不可用的功能加载转换插件。我们都准备好了语法。接下来让我们看看 polyfill。

¥Now the env preset will only load transformation plugins for features that are not available in our target browsers. We're all set for syntax. Let's look at polyfills next.

Polyfill

🚨 从 Babel 7.4.0 开始,这个包已经被弃用,取而代之的是直接包含 core-js/stable(以填充 ECMAScript 特性):

¥🚨 As of Babel 7.4.0, this package has been deprecated in favor of directly including core-js/stable (to polyfill ECMAScript features):

JavaScript
import "core-js/stable";

如果你将生成器或异步函数编译到 ES5,并且你使用的是早于 7.18.0@babel/core@babel/plugin-transform-regenerator 版本,则还必须加载 regenerator runtime 包。使用 @babel/preset-envuseBuiltIns: "usage" 选项或 @babel/plugin-transform-runtime 时会自动加载。

¥If you are compiling generators or async function to ES5, and you are using a version of @babel/core or @babel/plugin-transform-regenerator older than 7.18.0, you must also load the regenerator runtime package. It is automatically loaded when using @babel/preset-env's useBuiltIns: "usage" option or @babel/plugin-transform-runtime.

@babel/polyfill 模块包括 core-js 和自定义 再生器运行时 以模拟完整的 ES2015+ 环境。

¥The @babel/polyfill module includes core-js and a custom regenerator runtime to emulate a full ES2015+ environment.

这意味着你可以使用新的内置函数(如 PromiseWeakMap)、静态方法(如 Array.fromObject.assign)、实例方法(如 Array.prototype.includes)和生成器函数(与再生器插件一起使用时)。为了做到这一点,polyfill 添加到全局作用域以及像 String 这样的原生原型。

¥This means you can use new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions (when used alongside the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like String in order to do this.

对于库/工具作者来说,这可能太多了。如果你不需要像 Array.prototype.includes 这样的实例方法,你可以通过使用 转换运行时 插件而不是 @babel/polyfill 来完全不污染全局作用域。

¥For library/tool authors this may be too much. If you don't need the instance methods like Array.prototype.includes you can do without polluting the global scope altogether by using the transform runtime plugin instead of @babel/polyfill.

更进一步,如果你确切知道需要 polyfill 的功能,你可以直接从 core-js 中请求它们。

¥To go one step further, if you know exactly what features you need polyfills for, you can require them directly from core-js.

由于我们正在构建一个应用,我们只需安装 @babel/polyfill

¥Since we're building an application we can just install @babel/polyfill:

npm install --save @babel/polyfill

注意 --save 选项而不是 --save-dev 因为这是一个需要在源代码之前运行的 polyfill。

¥Note the --save option instead of --save-dev as this is a polyfill that needs to run before your source code.

现在对我们来说幸运的是,我们正在使用 env 预设,它有一个 "useBuiltIns" 选项,当设置为 "usage" 时,实际上将应用上面提到的最后一个优化,你只包含你需要的 polyfill。使用这个新选项,配置更改如下:

¥Now luckily for us, we're using the env preset which has a "useBuiltIns" option that when set to "usage" will practically apply the last optimization mentioned above where you only include the polyfills you need. With this new option the configuration changes like this:

babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage"
}
]
]
}

Babel 现在将检查你的所有代码以查找目标环境中缺少的功能,并且仅包含所需的 polyfill。例如这段代码:

¥Babel will now inspect all your code for features that are missing in your target environments and include only the required polyfills. For example this code:

JavaScript
Promise.resolve().finally();

会变成这样(因为 Edge 17 没有 Promise.prototype.finally):

¥would turn into this (because Edge 17 doesn't have Promise.prototype.finally):

JavaScript
require("core-js/modules/es.promise.finally");

Promise.resolve().finally();

如果我们不使用 env 预设并将 "useBuiltIns" 选项设置为 "usage"(默认为 "false"),我们将不得不在任何其他代码之前在我们的入口点只引入一次完整的 polyfill。

¥If we weren't using the env preset with the "useBuiltIns" option set to "usage" (defaults to "false") we would've had to require the full polyfill only once in our entry point before any other code.

例如:

¥For example:

babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "entry"
}
]
]
}

然后首先导入 core-js(以填充 ECMAScript 特性),在我们的入口文件中模拟完整的 ES2015+ 环境,因为 @babel/polyfill 已经 已弃用

¥Then import core-js (to polyfill ECMAScript features) first, in our entry file to emulate a full ES2015+ environment since @babel/polyfill has been deprecated:

JavaScript
 import "core-js/stable";

总结

¥Summary

我们使用 @babel/cli 从终端运行 Babel,使用 @babel/polyfill 填充所有新的 JavaScript 功能,使用 env 预设仅包含我们使用的功能和目标浏览器中缺少的功能的转换和填充。

¥We used @babel/cli to run Babel from the terminal, @babel/polyfill to polyfill all the new JavaScript features, and the env preset to only include the transformations and polyfills for the features that we use and that are missing in our target browsers.

有关使用构建系统、IDE 等设置 Babel 的更多信息,请查看我们的 交互式设置指南

¥For more information on setting up Babel with your build system, IDE, and more, check out our interactive setup guide.