Skip to main content

选项

选项可以通过多种方式传递给 Babel。当直接传递给 Babel 时,你可以只传递 options 对象。当通过封装器使用 Babel 时,可能还需要,或者至少更有用的是,通过 配置文件 传递选项。

¥Options can be passed to Babel in a variety of ways. When passed directly to Babel, you can just pass the options object. When Babel is used via a wrapper, it may also be necessary, or at least more useful, to pass the options via configuration files.

如果通过 @babel/cli 传递选项,则需要 kebab-case 名称。IE。

¥If passing options via @babel/cli you'll need to kebab-case the names. i.e.

npx babel --root-mode upward file.js # equivalent of passing the rootMode config option

主要选项

¥Primary options

这些选项只允许作为 Babel 的编程选项的一部分,因此它们主要供封装 Babel 的工具或直接调用 babel.transform 的人使用。Babel 集成的用户,如 babel-loader@babel/register 不太可能使用这些。

¥These options are only allowed as part of Babel's programmatic options, so they are primarily for use by tools that wrap around Babel, or people calling babel.transform directly. Users of Babel's integrations, like babel-loader or @babel/register are unlikely to use these.

cwd

类型:string
默认值:process.cwd()

¥Type: string
Default: process.cwd()

程序选项中的所有路径都将相对于解析的工作目录。

¥The working directory that all paths in the programmatic options will be resolved relative to.

caller

类型:一个形状为

¥Type: An object with the shape of

interface CallerData {
name: string;
supportsStaticESM?: boolean;
supportsDynamicImport?: boolean;
supportsTopLevelAwait?: boolean;
supportsExportNamespaceFrom?: boolean;
}
History
版本变化
v7.11.0添加 supportsExportNamespaceFrom
v7.7.0添加 supportsTopLevelAwait
v7.5.0添加 supportsDynamicImport

实用程序可以传递一个 caller 对象以向 Babel 标识自己,并传递与功能相关的标志以供配置、预设和插件使用。例如

¥Utilities may pass a caller object to identify themselves to Babel and pass capability-related flags for use by configs, presets and plugins. For example

JavaScript
babel.transformFileSync("example.js", {
caller: {
name: "my-custom-tool",
supportsStaticESM: true,
},
});

将允许插件和预设决定,由于支持 ES 模块,它们将跳过将 ES 模块编译为 CommonJS 模块。

¥would allow plugins and presets to decide that, since ES modules are supported, they will skip compilation of ES modules into CommonJS modules.

filename

类型:string

¥Type: string

与当前正在编译的代码关联的文件名(如果有)。文件名是可选的,但当文件名未知时,并非 Babel 的所有功能都可用,因为一部分选项依赖于文件名来实现其功能。

¥The filename associated with the code currently being compiled, if there is one. The filename is optional, but not all of Babel's functionality is available when the filename is unknown, because a subset of options rely on the filename for their functionality.

用户可能遇到的三种主要情况是:

¥The three primary cases users could run into are:

  • 文件名暴露给插件。一些插件可能需要文件名的存在。

    ¥The filename is exposed to plugins. Some plugins may require the presence of the filename.

  • "test""exclude""ignore" 等选项需要文件名才能进行字符串/正则表达式匹配。

    ¥Options like "test", "exclude", and "ignore" require the filename for string/RegExp matching.

  • .babelrc.json.babelrc 文件是相对于正在编译的文件加载的。如果省略此选项,Babel 的行为就像设置了 babelrc: false 一样。

    ¥.babelrc.json or .babelrc files are loaded relative to the file being compiled. If this option is omitted, Babel will behave as if babelrc: false has been set.

filenameRelative

类型:string
默认值:path.relative(opts.cwd, opts.filename)(如果 "filename" 通过了)

¥Type: string
Default: path.relative(opts.cwd, opts.filename) (if "filename" was passed)

用作 Babel 的 sourceFileName 选项的默认值,并用作 AMD / UMD / SystemJS 模块转换的文件名生成的一部分。

¥Used as the default value for Babel's sourceFileName option, and used as part of generation of filenames for the AMD / UMD / SystemJS module transforms.

code

类型:boolean
默认值:true

¥Type: boolean
Default: true

Babel 的默认返回值包括 codemap 属性以及生成的代码。在某些对 Babel 进行多次调用的情况下,禁用代码生成并改为使用 ast: true 直接获取 AST 以避免做不必要的工作会很有帮助。

¥Babel's default return value includes code and map properties with the resulting generated code. In some contexts where multiple calls to Babel are being made, it can be helpful to disable code generation and instead use ast: true to get the AST directly in order to avoid doing unnecessary work.

ast

类型:boolean
默认值:false

¥Type: boolean
Default: false

Babel 的默认设置是生成一个字符串和一个源映射,但在某些情况下,获取 AST 本身可能很有用。其主要用例将是多个变换通道链,沿线

¥Babel's default is to generate a string and a sourcemap, but in some contexts it can be useful to get the AST itself. The primary use case for this would be a chain of multiple transform passes, along the lines of

JavaScript
const filename = "example.js";
const source = fs.readFileSync(filename, "utf8");

// Load and compile file normally, but skip code generation.
const { ast } = babel.transformSync(source, {
filename,
ast: true,
code: false,
});

// Minify the file in a second pass and generate the output code here.
const { code, map } = babel.transformFromAstSync(ast, source, {
filename,
presets: ["minify"],
babelrc: false,
configFile: false,
});

注意:这个选项默认是不启用的,因为大多数用户不需要它,而且我们希望最终向 Babel 添加一个缓存层。必须缓存 AST 结构将占用更多空间。

¥Note: This option is not on by default because the majority of users won't need it and because we'd like to eventually add a caching layer to Babel. Having to cache the AST structure will take significantly more space.

cloneInputAst

类型:boolean
默认值:true
添加于 v7.11.0

¥Type: boolean
Default: true
Added in v7.11.0

默认情况下,babel.transformFromAst 将克隆输入 AST 以避免突变。如果输入 AST 没有在其他地方使用,则指定 cloneInputAst: false 可以提高解析性能。

¥By default babel.transformFromAst will clone the input AST to avoid mutations. Specifying cloneInputAst: false can improve parsing performance if the input AST is not used elsewhere.

配置加载选项

¥Config Loading options

加载配置可能会有点复杂,因为环境可以有多种类型的配置文件,并且这些配置文件可以有各种嵌套的配置对象,这些对象根据配置应用。

¥Loading configuration can get a little complex as environments can have several types of configuration files, and those configuration files can have various nested configuration objects that apply depending on the configuration.

root

类型:string
默认值:opts.cwd
安置:仅允许在 Babel 的程序化选项中

¥Type: string
Default: opts.cwd
Placement: Only allowed in Babel's programmatic options

将根据 "rootMode" 处理的初始路径,以确定当前 Babel 项目的概念根文件夹。这用于两种主要情况:

¥The initial path that will be processed based on the "rootMode" to determine the conceptual root folder for the current Babel project. This is used in two primary cases:

rootMode

类型:"root" | "upward" | "upward-optional"
默认值:"root"
安置:只允许在 Babel 的编程选项中
添加于:v7.1.0

¥Type: "root" | "upward" | "upward-optional"
Default: "root"
Placement: Only allowed in Babel's programmatic options
Added in: v7.1.0

这个选项,结合 "root" 值,定义了 Babel 如何选择它的项目根。不同的模式定义了 Babel 处理 "root" 值以获得最终项目根的不同方式。

¥This option, combined with the "root" value, defines how Babel chooses its project root. The different modes define different ways that Babel can process the "root" value to get the final project root.

注意:Babel 7.8.0 支持 babel.config.json。在旧的 Babel 7 版本中,仅支持 babel.config.js

¥Note: babel.config.json is supported from Babel 7.8.0. In older Babel 7 versions, only babel.config.js is supported.

"root" 是默认模式,因为它避免了 Babel 意外加载完全在当前项目文件夹之外的 babel.config.json 的风险。如果你使用 "upward-optional",请注意它会沿着目录结构一直走到文件系统根目录,并且总是可能有人在他们的主目录中忘记了 babel.config.json,这可能会导致你的构建出现意外错误。

¥"root" is the default mode because it avoids the risk that Babel will accidentally load a babel.config.json that is entirely outside of the current project folder. If you use "upward-optional", be aware that it will walk up the directory structure all the way to the filesystem root, and it is always possible that someone will have a forgotten babel.config.json in their home directory, which could cause unexpected errors in your builds.

具有基于每个包运行构建/测试的大仓项目结构的用户可能很想使用 "upward",因为大仓通常在项目根目录中有一个 babel.config.json。在没有 "upward" 的大仓子目录中运行 Babel,会导致 Babel 跳过加载项目根目录中的任何 babel.config.json 文件,这可能会导致意外错误和编译失败。

¥Users with monorepo project structures that run builds/tests on a per-package basis may well want to use "upward" since monorepos often have a babel.config.json in the project root. Running Babel in a monorepo subdirectory without "upward", will cause Babel to skip loading any babel.config.json files in the project root, which can lead to unexpected errors and compilation failure.

envName

类型:string
默认值:process.env.BABEL_ENV || process.env.NODE_ENV || "development"
安置:仅允许在 Babel 的程序化选项中

¥Type: string
Default: process.env.BABEL_ENV || process.env.NODE_ENV || "development"
Placement: Only allowed in Babel's programmatic options

配置加载期间使用的当前活动环境。该值在解析 "env" 配置时用作键,也可通过 api.env() 函数在配置函数、插件和预设中使用。

¥The current active environment used during configuration loading. This value is used as the key when resolving "env" configs, and is also available inside configuration functions, plugins, and presets, via the api.env() function.

configFile

类型:string | boolean
默认值:path.resolve(opts.root, "babel.config.json"),如果存在,则 false
放置:仅允许在 Babel 的程序化选项中

¥Type: string | boolean
Default: path.resolve(opts.root, "babel.config.json"), if it exists, false otherwise
Placement: Only allowed in Babel's programmatic options

默认搜索默认的 babel.config.json 文件,但可以传递任何 JS 或 JSON5 配置文件的路径。

¥Defaults to searching for a default babel.config.json file, but can be passed the path of any JS or JSON5 config file.

注意:此选项不会影响加载 .babelrc.json 文件,因此虽然执行 configFile: "./foo/.babelrc.json" 可能很诱人,但不建议这样做。如果给定的 .babelrc.json 是通过标准文件相关逻辑加载的,你最终将加载相同的配置文件两次,并将其与自身合并。如果你要链接特定的配置文件,建议坚持使用独立于 "babelrc" 名称的命名方案。

¥NOTE: This option does not affect loading of .babelrc.json files, so while it may be tempting to do configFile: "./foo/.babelrc.json", it is not recommended. If the given .babelrc.json is loaded via the standard file-relative logic, you'll end up loading the same config file twice, merging it with itself. If you are linking a specific config file, it is recommended to stick with a naming scheme that is independent of the "babelrc" name.

babelrc

类型:boolean
默认值:true 只要指定了 filename 选项
放置:在 Babel 的编程选项中或在加载的 "configFile" 中允许。编程选项将覆盖配置文件。

¥Type: boolean
Default: true as long as the filename option has been specified
Placement: Allowed in Babel's programmatic options, or inside of the loaded "configFile". A programmatic option will override a config file one.

true 将允许搜索 配置文件 和相对于提供给 Babel 的 "filename" 的旧版 .babelignore 文件。

¥true will enable searching for configuration files and the legacy .babelignore file relative to the "filename" provided to Babel.

在编程选项中传递的 babelrc 值将覆盖配置文件中的一组。

¥A babelrc value passed in the programmatic options will override one set within a configuration file.

注意:只有当当前 "filename" 位于与 "babelrcRoots" 包之一匹配的包内时,才会加载 .babelrc.json 文件。

¥Note: .babelrc.json files are only loaded if the current "filename" is inside of a package that matches one of the "babelrcRoots" packages.

babelrcRoots

类型:boolean | MatchPattern | Array<MatchPattern>
默认值:opts.root
安置:在 Babel 的编程选项中或在加载的 configFile 中允许。编程选项将覆盖配置文件。

¥Type: boolean | MatchPattern | Array<MatchPattern>
Default: opts.root
Placement: Allowed in Babel's programmatic options, or inside of the loaded configFile. A programmatic option will override a config file one.

默认情况下,Babel 只会在 "root" 包中搜索 .babelrc.json 文件,因为否则 Babel 无法知道给定的 .babelrc.json 是否应该被加载,或者是否已经安装了 "plugins""presets",因为正在编译的文件可能在 node_modules 中,或已符号链接到项目中。

¥By default, Babel will only search for .babelrc.json files within the "root" package because otherwise Babel cannot know if a given .babelrc.json is meant to be loaded, or if it's "plugins" and "presets" have even been installed, since the file being compiled could be inside node_modules, or have been symlinked into the project.

此选项允许用户在考虑是否加载 .babelrc.json 文件时提供应视为 "root" 包的其他包的列表。

¥This option allows users to provide a list of other packages that should be considered "root" packages when considering whether to load .babelrc.json files.

例如,希望允许单个包拥有自己的配置的大仓设置可能想要做

¥For example, a monorepo setup that wishes to allow individual packages to have their own configs might want to do

JavaScript
babelrcRoots: [
// Keep the root as a root
".",

// Also consider monorepo packages "root" and load their .babelrc.json files.
"./packages/*",
];

插件和预设选项

¥Plugin and Preset options

plugins

类型:Array<PluginEntry | Plugin> (PluginEntry)
默认值:[]

¥Type: Array<PluginEntry | Plugin> (PluginEntry)
Default: []

处理此文件时要激活的插件数组。有关单个条目如何交互的更多信息,尤其是在多个嵌套的 "env""overrides" 配置中使用时,请参阅 merging

¥An array of plugins to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested "env" and "overrides" configs, see merging.

注意:该选项还允许来自 Babel 本身的 Plugin 实例,但不建议直接使用这些实例。如果你需要创建插件或预设的持久表示,你应该使用 babel.createConfigItem()

¥Note: The option also allows Plugin instances from Babel itself, but using these directly is not recommended. If you need to create a persistent representation of a plugin or preset, you should use babel.createConfigItem().

presets

类型:Array<PresetEntry> (PresetEntry)
默认值:[]

¥Type: Array<PresetEntry> (PresetEntry)
Default: []

处理此文件时要激活的一组预设。有关单个条目如何交互的更多信息,尤其是在多个嵌套的 "env""overrides" 配置中使用时,请参阅 merging

¥An array of presets to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested "env" and "overrides" configs, see merging.

注意:预设的格式与插件相同,除了名称规范化需要 "preset-" 而不是 "plugin-",预设不能是 Plugin 的实例。

¥Note: The format of presets is identical to plugins, except for the fact that name normalization expects "preset-" instead of "plugin-", and presets cannot be instances of Plugin.

passPerPreset

类型:boolean
默认值:false
状态:已弃用

¥Type: boolean
Default: false
Status: Deprecated

指示 Babel 将 presets 数组中的每个预设作为独立通道运行。这个选项往往会给插件的确切顺序带来很多混乱,但如果你绝对需要在独立编译过程中运行一组操作,它会很有用。

¥Instructs Babel to run each of the presets in the presets array as an independent pass. This option tends to introduce a lot of confusion around the exact ordering of plugins, but can be useful if you absolutely need to run a set of operations as independent compilation passes.

注意:这个选项可能会在未来的 Babel 版本中被删除,因为我们添加了对定义插件之间顺序的更好的支持。

¥Note: This option may be removed in future Babel versions as we add better support for defining ordering between plugins.

输出目标

¥Output targets

targets

类型:string | Array<string> | { [string]: string }
默认值:{}
安置:允许在 Babel 的编程选项中,或在配置文件中
添加于:v7.13.0

¥Type: string | Array<string> | { [string]: string }
Default: {}
Placement: Allowed in Babel's programmatic options, or in config files
Added in: v7.13.0

History
版本变化
v7.20.0支持 deno 目标
v7.15.0支持 rhino 目标

描述你为项目支持/定位的环境。

¥Describes the environments you support/target for your project.

这可以是 browserslist-compatible 查询(使用 caveats):

¥This can either be a browserslist-compatible query (with caveats):

babel.config.json
{
"targets": "> 0.25%, not dead"
}

或支持的最低环境版本的对象:

¥Or an object of minimum environment versions to support:

babel.config.json
{
"targets": {
"chrome": "58",
"ie": "11"
}
}

支持的环境:androidchromedenoedgeelectronfirefoxieiosnodeoperarhinosafarisamsung

¥Supported environments: android, chrome, deno, edge, electron, firefox, ie, ios, node, opera, rhino, safari, samsung.

如果没有指定次要版本,Babel 会将其解释为 MAJOR.0。例如,"node": 12 将被视为 Node.js 12.0。

¥If a minor version is not specified, Babel will interpret it as MAJOR.0. For example, "node": 12 will be considered as Node.js 12.0.

没有目标

¥No targets

当没有指定目标时:Babel 会假设你的目标是最旧的浏览器。例如,@babel/preset-env 会将所有 ES2015-ES2020 代码转换为 ES5 兼容。

¥When no targets are specified: Babel will assume you are targeting the oldest browsers possible. For example, @babel/preset-env will transform all ES2015-ES2020 code to be ES5 compatible.

提示

我们建议设置 targets 以减小输出代码大小。

¥We recommend setting targets to reduce the output code size.

babel.config.json
{
"presets": ["@babel/preset-env"]
}

因此,Babel 的行为不同于 browserslist:当在你的 Babel 或浏览器列表配置中找不到目标时,它不会使用 defaults 查询。如果你想使用 defaults 查询,你需要明确地将它作为目标传递:

¥Because of this, Babel's behavior is different than browserslist: it does not use the defaults query when there are no targets are found in your Babel or browserslist config(s). If you want to use the defaults query, you will need to explicitly pass it as a target:

babel.config.json
{
"targets": "defaults"
}

我们认识到这并不理想,并将在 Babel v8 中重新审视这一点。

¥We recognize this isn’t ideal and will be revisiting this in Babel v8.

targets.esmodules

类型:boolean

¥Type: boolean

你还可以定位支持 ES 模块 的浏览器。当指定 esmodules 目标时,它将与 browsers 目标和 browserslist 的目标相交。你可以将此方法与 <script type="module"></script> 结合使用,以有条件地为用户提供更小的脚本 (https://jakearchibald.com/2017/es-modules-in-browsers/#nomodule-for-backwards-compatibility)。

¥You may also target browsers supporting ES Modules. When the esmodules target is specified, it will intersect with the browsers target and browserslist's targets. You can use this approach in combination with <script type="module"></script> to conditionally serve smaller scripts to users (https://jakearchibald.com/2017/es-modules-in-browsers/#nomodule-for-backwards-compatibility).

当同时指定 browsers 和 esmodules 目标时,它们将被相交。
babel.config.json
{
"targets": {
"esmodules": true
}
}

targets.node

类型:string | "current" | true

¥Type: string | "current" | true.

如果要针对当前节点版本进行编译,可以指定 "node": true"node": "current",这与 "node": process.versions.node 相同。

¥If you want to compile against the current node version, you can specify "node": true or "node": "current", which would be the same as "node": process.versions.node.

或者,你可以在 browserslist 查询中指定节点版本:

¥Alternatively, you can specify the node version in a browserslist query:

babel.config.json
{
"targets": "node 12" // not recommended
}

在这种情况下,browserslist 会将其解析为 node-releases 库中可用的最新版本。由于 Node.js 可能会在次要版本中支持新的语言功能,因此为 Node.js 12.22 生成的程序可能会在 Node.js 12.0 上引发语法错误。我们建议你在通过 browserslist 使用节点查询时始终指定次要版本:

¥In this case, browserslist will resolve it to the latest version available in the node-releases library. Because Node.js may support new language features in minor releases, a program generated for Node.js 12.22 may throw a syntax error on Node.js 12.0. We recommend that you always specify a minor version when using node queries with browserslist:

babel.config.json
{
"targets": "node 12.0"
}

targets.safari

类型:string | "tp"

¥Type: string | "tp".

如果要针对 Safari 的 技术预览 版本进行编译,可以指定 "safari": "tp"

¥If you want to compile against the technology preview version of Safari, you can specify "safari": "tp".

targets.browsers

类型:string | Array<string>

¥Type: string | Array<string>.

使用 browserslist 选择浏览器的查询(例如:最近 2 个版本,> 5%,safari tp)。

¥A query to select browsers (ex: last 2 versions, > 5%, safari tp) using browserslist.

请注意,浏览器的结果会被 targets 中的显式项覆盖。

¥Note, browsers' results are overridden by explicit items from targets.

targets.deno

类型:string

¥Type: string.

支持的最低版本为 1.0。

¥The minimum supported version is 1.0.

babel.config.json
{
"targets": {
"deno": "1.9"
}
}

browserslistConfigFile

类型:boolean
默认值:true
安置:允许在 Babel 的编程选项中,或在配置文件中
添加于:v7.13.0

¥Type: boolean
Default: true
Placement: Allowed in Babel's programmatic options, or in config files
Added in: v7.13.0

切换是否使用 浏览器列表配置源,包括搜索任何 browserslist 文件或引用 package.json 中的 browserslist 键。这对于使用 browserslist 配置文件的项目很有用,这些文件不会用 Babel 编译。

¥Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. This is useful for projects that use a browserslist config for files that won't be compiled with Babel.

如果指定了字符串,则它必须表示 browserslist 配置文件的路径。相对路径是相对于指定此选项的配置文件解析的,或者当它作为编程选项的一部分传递时解析为 cwd

¥If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies this option, or to cwd when it's passed as part of the programmatic options.

browserslistEnv

类型:string
默认值:undefined
安置:允许在 Babel 的编程选项中,或在配置文件中
添加于:v7.13.0

¥Type: string
Default: undefined
Placement: Allowed in Babel's programmatic options, or in config files
Added in: v7.13.0

浏览器列表环境 使用。

¥The Browserslist environment to use.

配置合并选项

¥Config Merging options

extends

类型:string
安置:不允许在预设内

¥Type: string
Placement: Not allowed inside of presets

Configs 可能 "extend" 其他配置文件。当前配置中的配置字段将是扩展文件配置之上的 merged

¥Configs may "extend" other configuration files. Config fields in the current config will be merged on top of the extended file's configuration.

env

类型:{ [envKey: string]: Options }
安置:不能嵌套在另一个 env 块内。

¥Type: { [envKey: string]: Options }
Placement: May not be nested inside of another env block.

允许只有在 envKeyenvName 选项匹配时才会启用的整个嵌套配置选项。

¥Allows for entire nested configuration options that will only be enabled if the envKey matches the envName option.

注意:env[envKey] 选项将是 merged 在根对象中指定的选项之上。

¥Note: env[envKey] options will be merged on top of the options specified in the root object.

overrides

类型:Array<Options>
安置:不得嵌套在另一个 overrides 对象内或 env 块内。

¥Type: Array<Options>
Placement: May not be nested inside of another overrides object, or within an env block.

允许用户提供一系列选项,这些选项一次将 merged 加入当前配置。此功能最好与 "test"/"include"/"exclude" 选项一起使用,以提供应应用覆盖的条件。例如:

¥Allows users to provide an array of options that will be merged into the current configuration one at a time. This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply. For example:

JavaScript
overrides: [{
test: "./vendor/large.min.js",
compact: true,
}],

可用于为已知较大和缩小的特定文件启用 compact 选项,并告诉 Babel 不要费心尝试很好地打印文件。

¥could be used to enable the compact option for one specific file that is known to be large and minified, and tell Babel not to bother trying to print the file nicely.

test

类型:MatchPattern | Array<MatchPattern>MatchPattern

¥Type: MatchPattern | Array<MatchPattern> (MatchPattern)

如果所有模式都不匹配,则当前配置对象被认为是非活动的,并在配置处理期间被忽略。此选项在 overrides 选项对象中使用时最有用,但它可以在任何地方使用。

¥If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it's allowed anywhere.

注意:这些切换不会影响前面部分中的编程和配置加载选项,因为它们在准备合并的配置之前很久就被考虑在内。

¥Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.

include

类型:MatchPattern | Array<MatchPattern>MatchPattern

¥Type: MatchPattern | Array<MatchPattern> (MatchPattern)

此选项是 "test" 的同义词。

¥This option is a synonym for "test".

exclude

类型:MatchPattern | Array<MatchPattern>MatchPattern

¥Type: MatchPattern | Array<MatchPattern> (MatchPattern)

如果任何模式匹配,则当前配置对象被认为是非活动的,并在配置处理期间被忽略。此选项在 overrides 选项对象中使用时最有用,但它可以在任何地方使用。

¥If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it's allowed anywhere.

注意:这些切换不会影响前面部分中的编程和配置加载选项,因为它们在准备合并的配置之前很久就被考虑在内。

¥Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.

ignore

类型:Array<MatchPattern> (MatchPattern)
安置:不允许在预设内

¥Type: Array<MatchPattern> (MatchPattern)
Placement: Not allowed inside of presets

如果任何模式匹配,Babel 将立即停止当前构建的所有处理。例如,用户可能想要做类似的事情

¥If any of the patterns match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like

JavaScript
ignore: ["./lib"];

显式禁用 lib 目录中文件的 Babel 编译。

¥to explicitly disable Babel compilation of files inside the lib directory.

注意:此选项禁用文件的所有 Babel 处理。虽然这有其用途,但也值得考虑将 "exclude" 选项作为一种不太激进的选择。

¥Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the "exclude" option as a less aggressive alternative.

only

类型:Array<MatchPattern> (MatchPattern)
安置:不允许在预设内

¥Type: Array<MatchPattern> (MatchPattern)
Placement: Not allowed inside of presets

如果所有模式都不匹配,Babel 将立即停止当前构建的所有处理。例如,用户可能想要做类似的事情

¥If all of the patterns fail to match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like

JavaScript
only: ["./src"];

显式启用 src 目录中文件的 Babel 编译,同时禁用其他所有内容。

¥to explicitly enable Babel compilation of files inside the src directory while disabling everything else.

注意:此选项禁用文件的所有 Babel 处理。虽然这有其用途,但也值得考虑将 "test"/"include" 选项作为一种不太激进的选择。

¥Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the "test"/"include" options as a less aggressive alternative.

源映射选项

¥Source Map options

inputSourceMap

类型:boolean | SourceMap
默认值:true

¥Type: boolean | SourceMap
Default: true

如果文件包含 //# sourceMappingURL=... 注释,true 将尝试从文件本身加载输入源映射。如果没有找到映射,或者映射无法加载和解析,它将被静默丢弃。

¥true will attempt to load an input sourcemap from the file itself, if it contains a //# sourceMappingURL=... comment. If no map is found, or the map fails to load and parse, it will be silently discarded.

如果提供了一个对象,它将被视为源映射对象本身。

¥If an object is provided, it will be treated as the source map object itself.

sourceMaps

类型:boolean | "inline" | "both"
默认值:false

¥Type: boolean | "inline" | "both"
Default: false

  • true 为代码生成源映射并将其包含在结果对象中。

    ¥true to generate a sourcemap for the code and include it in the result object.

  • "inline" 生成源映射并将其作为数据 URL 附加到代码末尾,但不包含在结果对象中。

    ¥"inline" to generate a sourcemap and append it as a data URL to the end of the code, but not include it in the result object.

  • "both" 与 inline 相同,但会将映射包含在结果对象中。

    ¥"both" is the same as inline, but will include the map in the result object.

配置文件中的选项对 @babel/cli 是否将文件与 .map 文件分开写入磁盘没有影响。当 --source-maps CLI 选项传递给 @babel/cli 时,它还将控制是否写入 .map 文件:

¥Options in configuration files have no effect on whether @babel/cli writes files separate .map files to disk. When the --source-maps CLI option is passed to @babel/cli it will also control whether .map files are written:

  • true 将映射写入磁盘上的 .map 文件

    ¥true will write the map to a .map file on disk

  • "inline" 会直接写入文件,所以会有一个 data: 包含映射

    ¥"inline" will write the file directly, so it will have a data: containing the map

  • "both" 将使用 data: URL 和 .map 写入文件。

    ¥"both" will write the file with a data: URL and also a .map.

注意:这些选项有点奇怪,因此根据你的用例,仅使用 true 并在你自己的代码中处理其余部分可能是最有意义的。

¥Note: These options are bit weird, so it may make the most sense to just use true and handle the rest in your own code, depending on your use case.

sourceMap

这是 sourceMaps 的同义词。推荐使用 sourceMaps

¥This is an synonym for sourceMaps. Using sourceMaps is recommended.

sourceFileName

类型:string
默认值:path.basename(opts.filenameRelative)(如果可用),或 "unknown"

¥Type: string
Default: path.basename(opts.filenameRelative) when available, or "unknown"

用于源映射对象内的文件的名称。

¥The name to use for the file inside the source map object.

sourceRoot

类型:string

¥Type: string

要在生成的源映射中设置的 sourceRoot 字段(如果需要)。

¥The sourceRoot fields to set in the generated source map, if one is desired.

杂项选项

¥Misc options

sourceType

类型:"script" | "module" | "unambiguous"
默认值:"module"

¥Type: "script" | "module" | "unambiguous"
Default: "module"

  • "script" - 使用 ECMAScript 脚本语法解析文件。不允许 import/export 语句,并且文件不是严格模式。

    ¥"script" - Parse the file using the ECMAScript Script grammar. No import/export statements allowed, and files are not in strict mode.

  • "module" - 使用 ECMAScript 模块语法解析文件。文件自动严格,允许 import/export 语句。

    ¥"module" - Parse the file using the ECMAScript Module grammar. Files are automatically strict, and import/export statements are allowed.

  • "unambiguous" - 如果存在 import/export 语句,则将文件视为 "module",否则将其视为 "script"。

    ¥"unambiguous" - Consider the file a "module" if import/export statements are present, or else consider it a "script".

unambiguous 在类型未知的上下文中非常有用,但它可能导致错误匹配,因为拥有不使用 import/export 语句的模块文件是完全有效的。

¥unambiguous can be quite useful in contexts where the type is unknown, but it can lead to false matches because it's perfectly valid to have a module file that does not use import/export statements.

此选项很重要,因为当前文件的类型会影响输入文件的解析,以及可能希望将 import/require 用法添加到当前文件的某些转换。

¥This option is important because the type of the current file affects both parsing of input files, and certain transforms that may wish to add import/require usage to the current file.

例如,@babel/plugin-transform-runtime 依赖于当前文档的类型来决定是插入 import 声明还是 require() 调用。@babel/preset-env 也为其 "useBuiltIns" 选项做同样的事情。由于 Babel 默认将文件处理为 ES 模块,因此通常这些插件/预设会插入 import 语句。设置正确的 sourceType 可能很重要,因为错误的类型会导致 Babel 将 import 语句插入到本来应该是 CommonJS 文件的文件中。这在正在执行 node_modules 依赖编译的项目中尤其重要,因为插入 import 语句会导致 Webpack 和其他工具将文件视为 ES 模块,从而破坏原本可以正常工作的 CommonJS 文件。

¥For instance, @babel/plugin-transform-runtime relies on the type of the current document to decide whether to insert an import declaration, or a require() call. @babel/preset-env also does the same for its "useBuiltIns" option. Since Babel defaults to treating files are ES modules, generally these plugins/presets will insert import statements. Setting the correct sourceType can be important because having the wrong type can lead to cases where Babel would insert import statements into files that are meant to be CommonJS files. This can be particularly important in projects where compilation of node_modules dependencies is being performed, because inserting an import statements can cause Webpack and other tooling to see a file as an ES module, breaking what would otherwise be a functional CommonJS file.

注意:此选项不会影响 .mjs 文件的解析,因为它们目前被硬编码为始终解析为 "module" 文件。

¥Note: This option will not affect parsing of .mjs files, as they are currently hard-coded to always parse as "module" files.

assumptions

类型:{ [assumption: string]: boolean }
默认值:{}
添加于:v7.13.0
安置:允许在编程选项、配置文件和预设中使用。

¥Type: { [assumption: string]: boolean }
Default: {}
Added in: v7.13.0
Placement: Allowed in programmatic options, config files and presets.

设置 Babel 可以做出的假设以产生更小的输出:

¥Set assumptions that Babel can make in order to produce smaller output:

babel.config.json
{
"assumptions": {
"iterableIsArray": true
},
"presets": ["@babel/preset-env"]
}

有关更多信息,请查看 assumptions 文档页面。

¥For more informations, check the assumptions documentation page.

highlightCode

类型:boolean
默认值:true

¥Type: boolean
Default: true

在 Babel 的错误消息中高亮代码片段中的标记,使其更易于阅读。

¥Highlight tokens in code snippets in Babel's error messages to make them easier to read.

wrapPluginVisitorMethod

类型:(key: string, nodeType: string, fn: Function) => Function

¥Type: (key: string, nodeType: string, fn: Function) => Function

允许用户在每个访问者上添加一个封装器,以便在 Babel 执行插件时检查访问者进程。

¥Allows users to add a wrapper on each visitor in order to inspect the visitor process as Babel executes the plugins.

  • key 是一个简单的不透明字符串,表示正在执行的插件。

    ¥key is a simple opaque string that represents the plugin being executed.

  • nodeType 是当前访问的 AST 节点的类型。

    ¥nodeType is the type of AST node currently being visited.

  • fn 是访问者函数本身。

    ¥fn is the visitor function itself.

用户可以返回一个替换函数,该替换函数应该在执行他们希望执行的任何日志记录和分析后调用原始函数。

¥Users can return a replacement function that should call the original function after performing whatever logging and analysis they wish to do.

parserOpts

类型:{}

¥Type: {}

一个不透明的对象,包含传递给正在使用的解析器的选项。

¥An opaque object containing options to pass through to the parser being used.

有关可用的解析器选项,请参阅 解析器选项

¥For available parser options, see Parser Options.

generatorOpts

类型:{}

¥Type: {}

一个不透明的对象,包含传递给正在使用的代码生成器的选项。有关最常用的选项,请参见 代码生成器选项

¥An opaque object containing options to pass through to the code generator being used. See Code Generator Options for most used options.

代码生成器选项

¥Code Generator options

retainLines

类型:boolean
默认值:false

¥Type: boolean
Default: false

Babel 将努力生成代码,以便将项目打印在与原始文件中相同的行上。存在此选项是为了让无法使用源映射的用户可以获得模糊有用的错误行号,但这只是尽力而为,并不保证在所有情况下都适用于所有插件。

¥Babel will make an effort to generate code such that items are printed on the same line that they were on in the original file. This option exists so that users who cannot use source maps can get vaguely useful error line numbers, but it is only a best-effort, and is not guaranteed in all cases with all plugins.

compact

类型:boolean | "auto"
默认值:"auto"

¥Type: boolean | "auto"
Default: "auto"

"auto" 将通过评估 code.length > 500_000 来设置值

¥"auto" will set the value by evaluating code.length > 500_000

在紧凑模式下生成代码时,将省略所有可选的换行符和空格。

¥All optional newlines and whitespace will be omitted when generating code in compact mode.

minified

类型:boolean
默认值:false

¥Type: boolean
Default: false

包括 compact: true,省略块尾分号,在可能的情况下从 new Foo() 中省略 (),并且可能输出较短版本的字面量。

¥Includes compact: true, omits block-end semicolons, omits () from new Foo() when possible, and may output shorter versions of literals.

auxiliaryCommentBefore

类型:string

¥Type: string

允许在原始文件中不存在的代码片段之前指定要插入的前缀注释。

¥Allows specifying a prefix comment to insert before pieces of code that were not present in the original file.

注意:原始文件中存在和不存在的定义可能有点难看,因此不建议使用此选项。如果你需要以某种方式注释代码,最好使用 Babel 插件。

¥Note: The definition of what is and isn't present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.

auxiliaryCommentAfter

类型:string

¥Type: string

允许在原始文件中不存在的代码片段之后指定要插入的前缀注释。

¥Allows specifying a prefix comment to insert after pieces of code that were not present in the original file.

注意:原始文件中存在和不存在的定义可能有点难看,因此不建议使用此选项。如果你需要以某种方式注释代码,最好使用 Babel 插件。

¥Note: The definition of what is and isn't present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.

comments

类型:boolean
默认值:true

¥Type: boolean
Default: true

如果没有给出函数,则为 shouldPrintComment 提供默认的注释状态。有关详细信息,请参阅该选项的默认值。

¥Provides a default comment state for shouldPrintComment if no function is given. See the default value of that option for more info.

shouldPrintComment

类型:(value: string) => boolean
默认无 minified(val) => opts.comments || /@license|@preserve/.test(val)
默认为 minified() => opts.comments

¥Type: (value: string) => boolean
Default without minified: (val) => opts.comments || /@license|@preserve/.test(val)
Default with minified: () => opts.comments

一个函数,可以决定给定的注释是否应该包含在 Babel 的输出代码中。

¥A function that can decide whether a given comment should be included in the output code from Babel.

高级用法

¥Advanced Usage

有关更多代码生成器选项,请参阅 生成器选项

¥For more code generator options, see Generator Options.

AMD / UMD / SystemJS 模块选项

¥AMD / UMD / SystemJS module options

moduleIds

类型:boolean
默认值:!!opts.moduleId

¥Type: boolean
Default: !!opts.moduleId

启用模块 ID 生成。

¥Enables module ID generation.

moduleId

类型:string

¥Type: string

用于模块的硬编码 ID。不能与 getModuleId 一起使用。

¥A hard-coded ID to use for the module. Cannot be used alongside getModuleId.

getModuleId

类型:(name: string) => string

¥Type: (name: string) => string

给定 babel 生成的模块名称,返回要使用的名称。返回一个虚假值将使用原始的 name

¥Given the babel-generated module name, return the name to use. Returning a falsy value will use the original name.

moduleRoot

类型:string

¥Type: string

包含在生成的模块名称上的根路径。

¥A root path to include on generated module names.

选项概念

¥Options Concepts

MatchPattern

类型:string | RegExp | (filename: string | void, context: { caller: { name: string } | void, envName: string, dirname: string ) => boolean

¥Type: string | RegExp | (filename: string | void, context: { caller: { name: string } | void, envName: string, dirname: string ) => boolean

几个 Babel 选项针对文件路径执行测试。通常,这些选项支持一种通用模式方法,其中每个模式都可以

¥Several Babel options perform tests against file paths. In general, these options support a common pattern approach where each pattern can be

  • string - 简单支持 *** 作为完整 slug 匹配的文件路径。与该模式匹配的任何文件或父文件夹都算作匹配。path follow 的 Node 的正常路径逻辑,所以在 POSIX 上必须是 /-separated,但在 Windows 上同时支持 /\

    ¥string - A file path with simple support for * and ** as full slug matches. Any file or parent folder matching the pattern counts as a match. The path follow's Node's normal path logic, so on POSIX is must be /-separated, but on Windows both / and \ are supported.

  • RegExp - 与规范化文件名匹配的正则表达式。在 POSIX 上,路径 RegExp 将针对 / 分隔的路径运行,而在 Windows 上,它将在 \ 分隔的路径上运行。

    ¥RegExp - A regular expression to match against the normalized filename. On POSIX the path RegExp will run against a /-separated path, and on Windows it will be on a \-separated path.

重要的是,如果使用其中任何一个,Babel 要求 filename 选项存在,否则会认为它是错误的。

¥Importantly, if either of these are used, Babel requires that the filename option be present, and will consider it an error otherwise.

  • (filename: string | void, context: { caller: { name: string } | void, envName: string, dirname: string }) => boolean 是一个通用回调,它应该返回一个布尔值来指示它是否匹配。如果没有给 Babel,函数会传递文件名或 undefined。它还传递了当前 envNamecaller 选项,这些选项是由对 Babel 和 dirname 的顶层调用指定的,它们是配置文件的目录或当前工作目录(如果以编程方式调用转换)。

    ¥(filename: string | void, context: { caller: { name: string } | void, envName: string, dirname: string }) => boolean is a general callback that should return a boolean to indicate whether it is a match or not. The function is passed the filename or undefined if one was not given to Babel. It is also passed the current envName and caller options that were specified by the top-level call to Babel and dirname that is either a directory of the configuration file or the current working directory (if the transformation was called programmatically).

合并

¥Merging

请参阅 Babel 如何合并配置项

¥Please refer to How Babel merges config items.

插件/预设条目

¥Plugin/Preset entries

PluginEntry / PresetEntry

单个插件/预设项可以有几种不同的结构:

¥Individual plugin/preset items can have several different structures:

  • EntryTarget - 个人插件

    ¥EntryTarget - Individual plugin

  • [EntryTarget, EntryOptions] - 带选项的个人插件

    ¥[EntryTarget, EntryOptions] - Individual plugin w/ options

  • [EntryTarget, EntryOptions, string] - 具有选项和名称的单个插件(有关名称的更多信息,请参阅 merging

    ¥[EntryTarget, EntryOptions, string] - Individual plugin with options and name (see merging for more info on names)

  • ConfigItem - babel.createConfigItem() 创建的一个插件配置项。

    ¥ConfigItem - A plugin configuration item created by babel.createConfigItem().

相同的 EntryTarget 可以多次使用,除非每个都被赋予不同的名称,这样做会导致重复插件/预设错误。

¥The same EntryTarget may be used multiple times unless each one is given a different name, and doing so will result in a duplicate-plugin/preset error.

这可能有点难以阅读,例如:

¥That can be a little hard to read, so as an example:

JavaScript
plugins: [
// EntryTarget
'@babel/plugin-transform-classes',

// [EntryTarget, EntryOptions]
['@babel/plugin-transform-arrow-functions', { spec: true }],

// [EntryTarget, EntryOptions, string]
['@babel/plugin-transform-for-of', { loose: true }, "some-name"],

// ConfigItem
babel.createConfigItem(require("@babel/plugin-transform-spread")),
],

EntryTarget

类型:string | {} | Function

¥Type: string | {} | Function

插件/预设目标可以来自几个不同的来源:

¥A plugin/preset target can come from a few different sources:

  • string - require 样式路径或插件/预设标识符。标识符将通过 名称规范化 传递。

    ¥string - A require-style path or plugin/preset identifier. Identifiers will be passed through name normalization.

  • {} | Function - require() 后的实际插件/预设对象或函数。

    ¥{} | Function - An actual plugin/preset object or function after it has been require()ed.

EntryOptions

类型:undefined | {} | false

¥Type: undefined | {} | false

选项在执行时传递给每个插件/预设。undefined 将被规范化为一个空对象。

¥Options are passed through to each plugin/preset when they are executed. undefined will be normalized to an empty object.

false 表示一个条目被完全禁用。这在排序很重要的情况下很有用,但需要一个单独的条件来决定是否启用了某些东西。例如:

¥false indicates that an entry is entirely disabled. This can be useful in contexts where ordering is important, but a separate condition is needed to decide if something is enabled. For instance:

JavaScript
plugins: [
'one',
['two', false],
'three',
],
overrides: [{
test: "./src",
plugins: [
'two',
]
}]

将为 src 中的文件启用 two 插件,但 two 仍将在 onethree 之间执行。

¥would enable the two plugin for files in src, but two would still execute between one and three.

名称规范化

¥Name Normalization

默认情况下,Babel 期望插件的名称中有 babel-plugin-babel-preset- 前缀。为了避免重复,Babel 有一个名称规范化阶段会在加载项目时自动添加这些前缀。这归结为几个主要规则:

¥By default, Babel expects plugins to have a babel-plugin- or babel-preset- prefix in their name. To avoid repetition, Babel has a name normalization phase will automatically add these prefixes when loading items. This boils down to a few primary rules:

  • 绝对路径原封不动地通过。

    ¥Absolute paths pass through untouched.

  • ./ 开头的相对路径原封不动地通过。

    ¥Relative paths starting with ./ pass through untouched.

  • 对包中文件的引用保持不变。

    ¥References to files within a package are untouched.

  • 任何以 module: 为前缀的标识符都将删除前缀,否则将保持不变。

    ¥Any identifier prefixed with module: will have the prefix removed but otherwise be untouched.

  • plugin-/preset- 将在任何没有它作为前缀的 @babel 范围的包的开头注入。

    ¥plugin-/preset- will be injected at the start of any @babel-scoped package that doesn't have it as a prefix.

  • babel-plugin-/babel-preset- 将作为前缀注入任何没有它作为前缀的无范围包。

    ¥babel-plugin-/babel-preset- will be injected as a prefix any unscoped package that doesn't have it as a prefix.

  • babel-plugin-/babel-preset- 将作为前缀注入任何名称中没有任何 @ 范围的包。

    ¥babel-plugin-/babel-preset- will be injected as a prefix any @-scoped package that doesn't have it anywhere in their name.

  • 如果仅给出 @ 范围名称,则 babel-plugin/babel-preset 将作为包名称注入。

    ¥babel-plugin/babel-preset will be injected as the package name if only the @-scope name is given.

以下是一些在插件上下文中应用时的示例:

¥Here are some examples, when applied in a plugin context:

输入归一化
"/dir/plugin.js""/dir/plugin.js"
"./dir/plugin.js""./dir/plugin.js"
"mod""babel-plugin-mod"
"mod/plugin""mod/plugin"
"babel-plugin-mod""babel-plugin-mod"
"@babel/mod""@babel/plugin-mod"
"@babel/plugin-mod""@babel/plugin-mod"
"@babel/mod/plugin""@babel/mod/plugin"
"@scope""@scope/babel-plugin"
"@scope/babel-plugin""@scope/babel-plugin"
"@scope/mod""@scope/babel-plugin-mod"
"@scope/babel-plugin-mod""@scope/babel-plugin-mod"
"@scope/prefix-babel-plugin-mod""@scope/prefix-babel-plugin-mod"
"@scope/mod/plugin""@scope/mod/plugin"
"module:foo""foo"