选项
选项可以通过多种方式传递给 Babel。当直接传递给 Babel 时,你只需传递选项对象。当通过封装器使用 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 这些名字。例如。
🌐 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;
}
历史
| 版本 | 变更 |
|---|---|
| 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
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:
- 文件名会暴露给插件。有些插件可能需要文件名的存在。
- 像
"test"、"exclude"和"ignore"这样的选项需要文件名来进行字符串/正则匹配。 .babelrc.json或.babelrc文件是相对于正在编译的文件加载的。如果省略此选项,Babel 会表现得就像已经设置了babelrc: false一样。
filenameRelative
类型:string
默认:path.relative(opts.cwd, opts.filename)(如果传入了 "filename")
作为 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 的默认返回值包含带有生成代码的 code 和 map 属性。在某些多次调用 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的默认设置是生成一个字符串和一个sourcemap,但在某些情况下,直接获取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
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 的编程选项中使用
将根据 "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 three primary cases:
- 检查默认
"configFile"值时的基础目录 ["babelrcRoots"](#babelrcroots)的默认值- 可以从源文件中的相对
sourceMappingURL解析的基础目录。任何不在root内的源映射都会被忽略。
rootMode
类型:"root" | "upward" | "upward-optional"
默认值:"root"
位置:只允许在 Babel 的编程选项中使用
新增于: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.config.json 从 Babel 7.8.0 开始支持。在较旧的 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"- 将"root"的值原样传递。"upward"- 从"root"目录向上查找,寻找包含babel.config.json文件的目录,如果没有找到babel.config.json就会报错。"upward-optional"- 从"root"目录向上走,寻找包含babel.config.json文件的目录,如果没找到babel.config.json,则回退到"root"。
"root" 是默认模式,因为它可以避免 Babel 意外加载完全位于当前项目文件夹之外的 babel.config.json。如果你使用 "upward-optional",要注意它会一直向上搜索目录结构直到文件系统根目录,并且总有可能有人在他们的主目录里遗忘了一个 babel.config.json,这可能会在你的构建中引发意外错误。
对于那些按每个包运行构建/测试的 monorepo 项目结构的用户来说,很可能想使用 "upward",因为 monorepo 的项目根目录通常有一个 babel.config.json。在 monorepo 的子目录中运行 Babel 而没有 "upward",会导致 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 的编程选项中使用
当前在配置加载期间使用的活动环境。这个值在解析 "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 的编程选项中使用
默认会搜索一个默认的 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" 里。编程选项会覆盖配置文件中的设置。
true 将支持根据提供给 Babel 的 "filename" 搜索 配置文件 和传统的 .babelignore 文件。
在程序选项中传入的 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 内。编程选项会覆盖配置文件中的设置。
默认情况下,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 文件时应被视为“根”包。
🌐 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
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)
默认:[]
在处理此文件时要激活的一系列插件。关于各个条目如何相互作用的更多信息,尤其是在跨多个嵌套 "env" 和 "overrides" 配置使用时,请参见 合并。
🌐 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)
默认:[]
处理此文件时要激活的一组预设。关于各个条目如何相互作用的更多信息,尤其是在多个嵌套的 "env" 和 "overrides" 配置中使用时,请参见 合并。
🌐 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
状态:已弃用
指示 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
历史
| 版本 | 变更 |
|---|---|
v7.20.0 | 支持 deno 目标 |
v7.15.0 | 支持 rhino 目标 |
描述你为项目支持/定位的环境。
🌐 Describes the environments you support/target for your project.
这可以是一个browserslist 兼容的查询(带有注意事项):
🌐 This can either be a browserslist-compatible query (with caveats):
{
"targets": "> 0.25%, not dead"
}
或支持的最低环境版本的对象:
🌐 Or an object of minimum environment versions to support:
{
"targets": {
"chrome": "58",
"ie": "11"
}
}
支持的环境:android、chrome、deno、edge、electron、firefox、ie、ios、node、opera、rhino、safari、samsung。
🌐 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 会默认你使用的是 browserslist defaults 查询,它涵盖了大多数现代浏览器。如果你想支持旧版浏览器,可以指定 targets 选项。
🌐 When no targets are specified: Babel will assume you are using the browserslist defaults query, which covers most modern browsers. If you want to support legacy browsers, specify the targets option.
targets.esmodules
类型:boolean | "交集"
🌐 Type: boolean | "intersect"
历史
| 版本 | 变更 |
|---|---|
v7.13.0 | 支持 "intersect" |
You may also target browsers supporting ES Modules. When the esmodules option is "intersect", 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).
{
// Resolve to "Chrome 61+, FF60+, Safari 11+"
"targets": {
"esmodules": "intersect", // Chrome 61+, FF 60+, Safari 10.1+
"browsers": "chrome 58, firefox 60, safari 11"
}
}
esmodules: true 是 esmodules: "intersect" 的别名。
如果你使用 browserslist defaults 作为目标,或者你计划支持在 2019 年及之后发布的任何主流浏览器,那么你可以放心地移除 esmodules,因为这些浏览器已经支持 ES 模块。
targets.node
类型:string | "current" | true。
🌐 Type: string | "current" | true.
如果你想针对当前的 Node 版本进行编译,你可以指定 "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:
{
"targets": "node 12" // not recommended
}
在这种情况下,browserslist 会把它解析为 node-releases 库中可用的最新版本。由于 Node.js 可能在次要版本中支持新的语言特性,为 Node.js 12.22 生成的程序在 Node.js 12.0 上可能会抛出语法错误。我们建议在使用 browserslist 的 node 查询时,总是指定次要版本:
🌐 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:
{
"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>.
一个查询,用于选择浏览器(例如:最近两个版本,>5%,safari tp),使用 browserslist。
🌐 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.
{
"targets": {
"deno": "1.9"
}
}
browserslistConfigFile
类型:boolean
默认值:true
位置:可在 Babel 的编程选项或配置文件中使用
添加于:v7.13.0
切换是否使用 browserslist 配置来源,这包括搜索任何 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
要使用的 Browserslist 环境。
🌐 The Browserslist environment to use.
配置合并选项
🌐 Config Merging options
extends
类型:string
位置:不允许在预设中使用
配置可以“扩展”其他配置文件。当前配置中的配置字段将合并到被扩展文件的配置之上。
🌐 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 块里面。
允许整个嵌套的配置选项,只有当 envKey 与 envName 选项匹配时才会启用。
🌐 Allows for entire nested configuration options that will only be enabled
if the envKey matches the envName option.
注意:env[envKey] 选项将会 合并 到根对象中指定的选项之上。
🌐 Note: env[envKey] options will be merged on top of the options specified in
the root object.
overrides
类型:Array<Options>
放置:不能嵌套在另一个 overrides 对象中,也不能在 env 块内。
允许用户提供一个选项数组,这些选项将会一次一个地合并到当前配置中。这个功能最好与"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:
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)
如果所有模式都不匹配,当前的配置对象将被视为不活动,并在配置处理过程中被忽略。这个选项在 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)
这个选项是 "test" 的同义词。
🌐 This option is a synonym for "test".
exclude
类型: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)
放置:不允许在预设中
如果任何模式匹配,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
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)
放置:不允许在预设中
如果所有模式都无法匹配,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
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
true 会尝试从文件本身加载输入源映射,如果文件中包含 //# sourceMappingURL=... 注释。如果找不到映射,或者映射加载或解析失败,它会被静默丢弃。
如果提供了一个对象,它将被视为源映射对象本身。
🌐 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为代码生成一个源映射并将其包含在结果对象中。"inline"生成一个源映射并将其作为数据 URL 附加到代码末尾,但不将其包含在结果对象中。"both"和 inline 一样,但会把地图包含在结果对象中。
配置文件中的选项不会影响 @babel/cli 是否将文件单独写入 .map 文件到磁盘。当 --source-maps 命令行选项传递给 @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文件"inline"会直接写入文件,所以它会有一个包含映射的data:"both"会用data:URL 写入文件,并且还会有一个.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" | "commonjs" | "unambiguous"
默认:"module"
"script"- 使用 ECMAScript 脚本语法解析文件。不允许使用import/export语句,并且文件不是严格模式。"module"- 使用 ECMAScript 模块语法解析文件。文件默认是严格模式,并且允许使用import/export语句。"commonjs"- 将文件解析为在 CommonJS 环境中运行。这一选项在转换.cjs源时推荐使用。有关"script"和"commonjs"语法差异,请参见 Parser 文档。"unambiguous"- 如果存在import/export语句,就把这个文件当作“模块”,否则就当作“脚本”。
unambiguous 在类型未知的情况下可能非常有用,但它也可能导致错误匹配,因为完全有可能存在一个模块文件没有使用 import/export 语句。
这个选项很重要,因为当前文件的类型会影响输入文件的解析,以及某些可能希望在当前文件中添加 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 在原本是 CommonJS 文件的情况下插入 import 语句。这在需要编译 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
位置: 允许在程序化选项、配置文件和预设中使用。
设置 Babel 可以做出的假设以产生更小的输出:
🌐 Set assumptions that Babel can make in order to produce smaller output:
{
"assumptions": {
"iterableIsArray": true
},
"presets": ["@babel/preset-env"]
}
想了解更多信息,请查看 假设 文档页面。
🌐 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是一个简单的不透明字符串,用来表示正在执行的插件。nodeType是当前正在访问的 AST 节点类型。fn本身就是访问者函数。
用户可以返回一个替代函数,这个函数在执行他们想做的任何日志记录和分析之后应该调用原来的函数。
🌐 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 来设置数值
在紧凑模式下生成代码时,所有可选的换行和空格都会被省略。
🌐 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- 一个简单支持**、*和*.ext的文件路径。任何符合模式的文件或父文件夹都会被视为匹配。路径遵循 Node 的普通路径逻辑,所以在 POSIX 系统上必须使用/分隔符,但在 Windows 上既支持/也支持\。RegExp- 用于匹配规范化文件名的正则表达式。在 POSIX 上,路径正则会针对用/分隔的路径运行,而在 Windows 上,它会针对用\分隔的路径运行。
重要的是,如果使用其中任何一个,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。它还会传入当前的envName和caller选项,这些选项是在顶层调用 Babel 时指定的,以及dirname,它要么是配置文件所在的目录,要么是当前工作目录(如果是以程序方式调用转换的话)。
基于字符串的匹配 不 支持完整的通配符模式。** 匹配 0 个或多个路径部分,* 精确匹配 1 个路径部分,*.ext 匹配带有扩展名的通配符。以其他方式使用 *(比如作为路径或文件名的一部分)是不支持的。如果你需要复杂的模式匹配,可以使用正则匹配,或者在配置中自定义函数。
以下是一些匹配工作原理的示例:
🌐 Here are some examples, on how matching works:
| 描述 | 模式 | 匹配 | 不匹配 |
|---|---|---|---|
| 精确路径匹配 | foo/bar | /src/foo/bar | /src/foo、/src/foo/baz、/src/foo/bar/baz |
单通配符 (*) | */bar | /src/foo/bar、/src/xyz/bar | /src/foo/baz、/src/bar、/src/foo/bar/baz |
双通配符 (**) | **/bar | /src/bar、/src/foo/bar、/src/a/b/c/bar | /src/bar/foo、/src/barfoo |
文件扩展名模式 (*.ext) | foo/*.js | /src/foo/test.js、/src/foo/index.js/ | /src/foo/test.ts、/src/foo/test.js.map |
| 组合模式 | **/test/*.js | /src/test/file.js、/src/a/b/test/file.js | /src/test.js、/src/test/sub/file.js |
以下是一些例子,其中 * 没有 通配符功能:
🌐 Here are examples, where * does not have a wildcard function:
| 描述 | 模式 | 不匹配 |
|---|---|---|
| 路径中的星号 | test*me/*.js | /src/testme/1.js, /src/testme/2.js, /src/test-me/3.js |
| 文件名中的星号 | foo*bar.js | /src/foobar.js, /src/foo-bar.js |
| 扩展名中的星号 | file.ts* | /src/file.ts, /src/file.tsx |
合并
🌐 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, EntryOptions]- 带选项的个人插件[EntryTarget, EntryOptions, string]- 带有选项和名称的单独插件(有关名称的更多信息,请参见合并)ConfigItem-babel.createConfigItem()创建的插件配置项。
同一个 EntryTarget 可以多次使用,除非给每个 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:
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风格的路径或插件/预设标识符。标识符将通过 名称规范化 处理。{} | Function- 一个实际的插件/预设对象或函数,在它被require()之后。
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 表示某个条目被完全禁用。在需要考虑顺序的情况下,这会很有用,但还需要一个单独的条件来决定某个东西是否启用。例如:
plugins: [
'one',
['two', false],
'three',
],
overrides: [{
test: "./src",
plugins: [
'two',
]
}]
会为 src 中的文件启用 two 插件,但 two 仍会在 one 和 three 之间执行。
🌐 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:
- 绝对路径原封不动地通过。
- 以
./开头的相对路径会原样通过。 - 对包内文件的引用不会被修改。
- 任何以
module:为前缀的标识符,其前缀会被移除,但其他部分保持不变。 plugin-/preset-会在任何没有它作为前缀的@babel范围包的开头被注入。babel-plugin-/babel-preset-会被注入为任何没有该前缀的未作用域包的前缀。babel-plugin-/babel-preset-将作为前缀注入到任何@范围的包中,只要它们的名字里 任意位置 没有该前缀。- 如果只提供
@范围名,babel-plugin/babel-preset将被作为包名注入。
以下是一些在插件上下文中应用时的示例:
🌐 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" |