Skip to main content

@babel/preset-env

@babel/preset-env 是一个智能预设,允许你使用最新的 JavaScript,而无需微观管理目标环境需要哪些语法转换(以及可选的浏览器 polyfill)。这既让你的生活更轻松,也让 JavaScript 包更小!

¥@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!

安装

¥Install

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

它是如何工作的?

¥How Does it Work?

如果没有一些很棒的开源项目,比如 browserslistcompat-tableelectron-to-chromium@babel/preset-env 是不可能的。

¥@babel/preset-env would not be possible if not for a number of awesome open-source projects, like browserslist, compat-table, and electron-to-chromium.

我们利用这些数据源来维护我们支持的 哪个版本的映射 个目标环境,这些环境获得了对 JavaScript 语法或浏览器功能的支持,以及这些语法和功能到 Babel 转换插件和 core-js 填充物的映射。

¥We leverage these data sources to maintain mappings of which version of our supported target environments gained support of a JavaScript syntax or browser feature, as well as a mapping of those syntaxes and features to Babel transform plugins and core-js polyfills.

注意

@babel/preset-env 不会包含任何低于第 3 阶段的 JavaScript 语法建议,因为在 TC39 流程的那个阶段,它不会被任何浏览器实现。这些将需要手动包含在内。shippedProposals 选项将包括一些浏览器已经实现的第 3 阶段提案。

¥@babel/preset-env won't include any JavaScript syntax proposals less than Stage 3 because at that stage in the TC39 process, it wouldn't be implemented by any browsers anyway. Those would need to be included manually. The shippedProposals option will include Stage 3 proposals that some browsers have already implemented.

@babel/preset-env 接受任何 你指定的目标环境 并根据其映射检查它们以编译插件列表并将其传递给 Babel。

¥@babel/preset-env takes any target environments you've specified and checks them against its mappings to compile a list of plugins and passes it to Babel.

浏览器列表集成

¥Browserslist Integration

对于基于浏览器或 Electron 的项目,我们建议使用 .browserslistrc 文件来指定目标。你可能已经拥有此配置文件,因为它被生态系统中的许多工具使用,例如 autoprefixerstylelinteslint-plugin-compat 和许多其他工具。

¥For browser- or Electron-based projects, we recommend using a .browserslistrc file to specify targets. You may already have this configuration file as it is used by many tools in the ecosystem, like autoprefixer, stylelint, eslint-plugin-compat and many others.

默认情况下,除非设置了 targetsignoreBrowserslistConfig 选项,否则 @babel/preset-env 将使用 浏览器列表配置源

¥By default @babel/preset-env will use browserslist config sources unless either the targets or ignoreBrowserslistConfig options are set.

提示

如果你依赖 browserslist 的默认查询(无论是明确的还是没有 browserslist 配置),你将需要查看 没有目标 部分以获取有关预设环境行为的信息。

¥If you are relying on browserslist's defaults query (either explicitly or by having no browserslist config), you will want to check out the No targets section for information on preset-env's behavior.

例如,仅包含浏览器市场份额 >0.25% 的用户所需的填充和代码转换(忽略没有安全更新的浏览器,如 IE 10 和 BlackBerry):

¥For example, to only include polyfills and code transforms needed for users whose browsers have >0.25% market share (ignoring browsers without security updates like IE 10 and BlackBerry):

babel.config.json
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry",
"corejs": "3.22"
}
]
]
}
.browserslistrc
> 0.25%
not dead

¥or

package.json
{ "browserslist": "> 0.25%, not dead" }
注意

请注意,从 v7.4.5 开始,browserslist 查询由 mobileToDesktop: true 解析。例如,如果要创建查询运行 npx browserslist --mobile-to-desktop ">0.25%, not dead" 的快照。

¥Please note that since v7.4.5 the browserslist query is resolved with mobileToDesktop: true. For example, if you want to create a snapshot of a query run npx browserslist --mobile-to-desktop ">0.25%, not dead".

选项

¥Options

有关设置预设选项的更多信息,请参阅 预设选项 文档。

¥For more information on setting options for a preset, refer to the preset options documentation.

targets

string | Array<string> | { [string]: string },如果在 @babel/preset-env 的文档中没有指定 browserslist 相关选项,则默认为顶层 targets 选项,否则为 {}

¥string | Array<string> | { [string]: string }, defaults to the top-level targets option if no browserslist-related option is specified in @babel/preset-env's docs, otherwise to {}.

有关用法,请参阅 targets 选项 文档。

¥For usage, refer to the targets option documentation.

bugfixes

boolean,默认为 false

¥boolean, defaults to false.

添加于:v7.9.0

¥Added in: v7.9.0

注意

Babel 8 中默认启用此选项。

¥This option will be enabled by default in Babel 8.

默认情况下,@babel/preset-env(和一般的 Babel 插件)将 ECMAScript 语法特性分组为密切相关的较小特性的集合。这些组可能很大并且包括很多边缘情况,例如 "函数参数" 包括 destructured、default 和 rest 参数。从这个分组信息中,Babel 根据你指定给 @babel/preset-envtargets 选项的浏览器支持目标启用或禁用每个组。

¥By default, @babel/preset-env (and Babel plugins in general) grouped ECMAScript syntax features into collections of closely related smaller features. These groups can be large and include a lot of edge cases, for example "function arguments" includes destructured, default and rest parameters. From this grouping information, Babel enables or disables each group based on the browser support target you specify to @babel/preset-env’s targets option.

启用此选项后,@babel/preset-env 会尝试将损坏的语法编译为目标浏览器支持的最接近的非损坏现代语法。根据你的 targets 以及你使用的现代语法的数量,这可能会导致已编译应用的大小显着减小。此选项合并了 @babel/preset-modules 的功能,而无需使用其他预设。

¥When this option is enabled, @babel/preset-env tries to compile the broken syntax to the closest non-broken modern syntax supported by your target browsers. Depending on your targets and on how many modern syntax you are using, this can lead to a significant size reduction in the compiled app. This option merges the features of @babel/preset-modules without having to use another preset.

spec

boolean,默认为 false

¥boolean, defaults to false.

为此预设中支持它们的任何插件启用更符合规范但可能更慢的转换。

¥Enable more spec compliant, but potentially slower, transformations for any plugins in this preset that support them.

提醒

该选项已被弃用,并将在 Babel 8 中删除。考虑迁移到自 Babel 7.13 以来可用的顶层 assumptions。请参阅 “从 @babel/preset-env"loose""spec" 模式迁移” 了解等效的基于假设的配置,准备复制并粘贴作为起点。

¥This option has been deprecated and will be removed in Babel 8. Consider migrating to the top level assumptions available since Babel 7.13. See "Migrating from @babel/preset-env's "loose" and "spec" modes" for the equivalent assumptions-based configuration, ready to be copied and pasted as a starting point.

loose

boolean,默认为 false

¥boolean, defaults to false.

为此预设中允许它们的任何插件启用 "loose" 转换

¥Enable "loose" transformations for any plugins in this preset that allow them.

提醒

该选项已被弃用,并将在 Babel 8 中删除。考虑迁移到自 Babel 7.13 以来可用的顶层 assumptions。请参阅 “从 @babel/preset-env"loose""spec" 模式迁移” 了解等效的基于假设的配置,准备复制并粘贴作为起点。

¥This option has been deprecated and will be removed in Babel 8. Consider migrating to the top level assumptions available since Babel 7.13. See "Migrating from @babel/preset-env's "loose" and "spec" modes" for the equivalent assumptions-based configuration, ready to be copied and pasted as a starting point.

modules

"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false,默认为 "auto"

¥"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false, defaults to "auto".

启用将 ES 模块语法转换为另一种模块类型。请注意,cjs 只是 commonjs 的别名。

¥Enable transformation of ES module syntax to another module type. Note that cjs is just an alias for commonjs.

将此设置为 false 将保留 ES 模块。仅当你打算将原生 ES 模块发送到浏览器时才使用此选项。如果你使用 Babel 的 bundler,默认的 modules: "auto" 总是首选。

¥Setting this to false will preserve ES modules. Use this only if you intend to ship native ES Modules to browsers. If you are using a bundler with Babel, the default modules: "auto" is always preferred.

modules: "auto"

默认情况下,@babel/preset-env 使用 caller 数据来确定是否应该转换 ES 模块和模块特性(例如 import())。通常 caller 数据将在 bundler 插件中指定(例如 babel-loader@rollup/plugin-babel),因此不建议自己传递 caller 数据 - 传递的 caller 可能会覆盖来自 bundler 插件的数据,并且将来如果 bundler 可能会得到次优结果支持新的模块功能。

¥By default @babel/preset-env uses caller data to determine whether ES modules and module features (e.g. import()) should be transformed. Generally caller data will be specified in the bundler plugins (e.g. babel-loader, @rollup/plugin-babel) and thus it is not recommended to pass caller data yourself -- The passed caller may overwrite the one from bundler plugins and in the future you may get suboptimal results if bundlers supports new module features.

debug

boolean,默认为 false

¥boolean, defaults to false.

输出到 console.logpreset-env 启用的 polyfills 和转换插件,如果适用,你的目标之一需要它。

¥Outputs to console.log the polyfills and transform plugins enabled by preset-env and, if applicable, which one of your targets that needed it.

include

Array<string|RegExp>,默认为 []

¥Array<string|RegExp>, defaults to [].

History
版本变化
v7.4.0支持注入 core-js@3 polyfills

始终包含的插件数组。

¥An array of plugins to always include.

有效选项包括:

¥Valid options include any:

  • Babel 插件 - 支持全名和简写名称,例如以下在功能上是等效的:

    ¥Babel plugins - both full and shorthand names are supported, for example the following are functionally equivalent:

    • @babel/plugin-transform-spread

    • @babel/transform-spread

    • babel-transform-spread

    • transform-spread

  • 内置插件(核心 js@2核心 js@3,例如 es.mapes.setes.object.assign

    ¥Built-ins (both for core-js@2 and core-js@3, such as es.map, es.set, or es.object.assign.

插件名称可以完全或部分指定(或使用 RegExp)。

¥Plugin names can be fully or partially specified (or using RegExp).

可接受的输入:

¥Acceptable inputs:

  • 全名(string):"es.math.sign"

    ¥Full name (string): "es.math.sign"

  • 部分名称(string):"es.math.*"(解析为所有带有 es.math 前缀的插件)

    ¥Partial name (string): "es.math.*" (resolves to all plugins with es.math prefix)

  • RegExp 对象:/^transform-.*$/new RegExp("^transform-modules-.*")

    ¥RegExp Object: /^transform-.*$/ or new RegExp("^transform-modules-.*")

请注意,上面的 . 是匹配任何字符的 RegExp,而不是实际的 '.' 字符。另请注意,为了匹配任何字符,RegExp 中使用了 .*,而不是 glob 格式中的 *

¥Note that the above . is the RegExp equivalent to match any character, and not the actual '.' character. Also note that to match any character .* is used in RegExp as opposed to * in glob format.

如果原生实现中存在错误,或者不支持的功能 + 支持的功能的组合不起作用,则此选项很有用。

¥This option is useful if there is a bug in a native implementation, or a combination of a non-supported feature + a supported one doesn't work.

例如,Node 4 支持原生类但不支持传播。如果 super 与扩展参数一起使用,则 @babel/plugin-transform-classes 转换需要为 included,否则无法使用 super 转换扩展。

¥For example, Node 4 supports native classes but not spread. If super is used with a spread argument, then the @babel/plugin-transform-classes transform needs to be included, as it is not possible to transpile a spread with super otherwise.

注意

includeexclude 选项仅适用于 此预设包含的插件;因此,例如,包含 @babel/plugin-proposal-do-expressions 或排除 @babel/plugin-proposal-function-bind 将引发错误。要使用此预设中未包含的插件,请将它们直接添加到你的 "插件"

¥The include and exclude options only work with the plugins included with this preset; so, for example, including @babel/plugin-proposal-do-expressions or excluding @babel/plugin-proposal-function-bind will throw errors. To use a plugin not included with this preset, add them to your "plugins" directly.

exclude

Array<string|RegExp>,默认为 []

¥Array<string|RegExp>, defaults to [].

始终排除/删除的插件数组。

¥An array of plugins to always exclude/remove.

可能的选项与 include 选项相同。

¥The possible options are the same as the include option.

此选项对于排除像 @babel/plugin-transform-regenerator 这样的转换非常有用,例如,如果你使用像 fast-async 这样的另一个插件而不是 Babel 的 async-to-gen

¥This option is useful for excluding a transform like @babel/plugin-transform-regenerator, for example if you are using another plugin like fast-async instead of Babel's async-to-gen.

useBuiltIns

"usage" | "entry" | false,默认为 false

¥"usage" | "entry" | false, defaults to false.

此选项配置 @babel/preset-env 如何处理 polyfill。

¥This option configures how @babel/preset-env handles polyfills.

当使用 usageentry 选项时,@babel/preset-env 将添加对 core-js 模块的直接引用作为裸导入(或引入)。这意味着 core-js 将相对于文件本身进行解析,并且需要可访问。

¥When either the usage or entry options are used, @babel/preset-env will add direct references to core-js modules as bare imports (or requires). This means core-js will be resolved relative to the file itself and needs to be accessible.

由于 @babel/polyfill 在 7.4.0 中已弃用,我们建议直接添加 core-js 并通过 corejs 选项设置版本。

¥Since @babel/polyfill was deprecated in 7.4.0, we recommend directly adding core-js and setting the version via the corejs option.

npm install core-js@3 --save

# or

npm install core-js@2 --save

useBuiltIns: 'entry'

History
版本变化
v7.4.0它取代了 "core-js/stable""regenerator-runtime/runtime" 条目导入
v7.0.0它取代了 "@babel/polyfill" 条目导入
tip

在整个应用中只使用一次 import "core-js";

¥Only use import "core-js"; once in your whole app.

如果你使用的是 @babel/polyfill,则它已包含 core-js:导入它两次会抛出错误。

¥If you are using @babel/polyfill, it already includes core-js: importing it twice will throw an error.

这些包的多次导入或引入可能会导致全局冲突和其他难以追踪的问题。我们建议创建一个仅包含 import 语句的条目文件。

¥Multiple imports or requires of those packages might cause global collisions and other issues that are hard to trace. We recommend creating a single entry file that only contains the import statements.

此选项启用一个新插件,该插件将 import "core-js/stable";require("core-js"); 语句替换为基于环境的不同 core-js 入口点的单独导入。

¥This option enables a new plugin that replaces the import "core-js/stable"; and require("core-js"); statements with individual imports to different core-js entry points based on environment.

输入

¥In

JavaScript
import "core-js";

Out(因环境而异)

¥Out (different based on environment)

JavaScript
import "core-js/modules/es.string.pad-start";
import "core-js/modules/es.string.pad-end";

导入 "core-js" 会为每个可能的 ECMAScript 特性加载 polyfill:如果你知道你只需要其中的一部分怎么办?使用 core-js@3 时,@babel/preset-env 能够优化每个 core-js 入口点及其组合。例如,你可能只想填充数组方法和新的 Math 提案:

¥Importing "core-js" loads polyfills for every possible ECMAScript feature: what if you know that you only need some of them? When using core-js@3, @babel/preset-env is able to optimize every single core-js entrypoint and their combinations. For example, you might want to only polyfill array methods and new Math proposals:

输入

¥In

JavaScript
import "core-js/es/array";
import "core-js/proposals/math-extensions";

Out(因环境而异)

¥Out (different based on environment)

JavaScript
import "core-js/modules/es.array.unscopables.flat";
import "core-js/modules/es.array.unscopables.flat-map";
import "core-js/modules/esnext.math.clamp";
import "core-js/modules/esnext.math.deg-per-rad";
import "core-js/modules/esnext.math.degrees";
import "core-js/modules/esnext.math.fscale";
import "core-js/modules/esnext.math.rad-per-deg";
import "core-js/modules/esnext.math.radians";
import "core-js/modules/esnext.math.scale";

你可以阅读 core-js 的文档以获取有关不同入口点的更多信息。

¥You can read core-js's documentation for more information about the different entry points.

注意

使用 core-js@2 时(显式使用 corejs: "2" 选项或隐式使用),@babel/preset-env 还将转换 @babel/polyfill 的导入和引入。此行为已弃用,因为无法将 @babel/polyfill 与不同的 core-js 版本一起使用。

¥When using core-js@2 (either explicitly using the corejs: "2" option or implicitly), @babel/preset-env will also transform imports and requires of @babel/polyfill. This behavior is deprecated because it isn't possible to use @babel/polyfill with different core-js versions.

useBuiltIns: 'usage'

在每个文件中使用 polyfill 时为它们添加特定的导入。我们利用了打包器只会加载相同的 polyfill 一次这一事实。

¥Adds specific imports for polyfills when they are used in each file. We take advantage of the fact that a bundler will load the same polyfill only once.

输入

¥In

a.js
var a = new Promise();
b.js
var b = new Map();

Out(如果环境不支持)

¥Out (if environment doesn't support it)

a.js
import "core-js/modules/es.promise";
var a = new Promise();
b.js
import "core-js/modules/es.map";
var b = new Map();

Out(如果环境支持)

¥Out (if environment supports it)

a.js
var a = new Promise();
b.js
var b = new Map();

useBuiltIns: false

不要为每个文件自动添加 polyfill,也不要将 import "core-js"import "@babel/polyfill" 转换为单独的 polyfill。

¥Don't add polyfills automatically per file, and don't transform import "core-js" or import "@babel/polyfill" to individual polyfills.

corejs

添加于:v7.4.0

¥Added in: v7.4.0

string{ version: string, proposals: boolean },默认为 "2.0"version 字符串可以是任何受支持的 core-js 版本。例如,"3.33""2.0"

¥string or { version: string, proposals: boolean }, defaults to "2.0". The version string can be any supported core-js versions. For example, "3.33" or "2.0".

此选项仅在与 useBuiltIns: usageuseBuiltIns: entry 一起使用时有效,并确保 @babel/preset-env 注入你的 core-js 版本支持的 polyfill。建议指定次要版本,否则 "3" 将被解释为 "3.0",它可能不包含最新功能的 polyfill。

¥This option only has an effect when used alongside useBuiltIns: usage or useBuiltIns: entry, and ensures @babel/preset-env injects the polyfills supported by your core-js version. It is recommended to specify the minor version otherwise "3" will be interpreted as "3.0" which may not include polyfills for the latest features.

默认情况下,只会注入用于稳定 ECMAScript 特性的 polyfill:如果你想 polyfill 提案,你有三种不同的选择:

¥By default, only polyfills for stable ECMAScript features are injected: if you want to polyfill proposals, you have three different options:

  • 使用 useBuiltIns: "entry" 时,直接导入一个 提案 polyfill 即可:import "core-js/proposals/string-replace-all"

    ¥when using useBuiltIns: "entry", you can directly import a proposal polyfill: import "core-js/proposals/string-replace-all".

  • 使用 useBuiltIns: "usage" 时,你有两种不同的选择:

    ¥when using useBuiltIns: "usage" you have two different alternatives:

    • shippedProposals 选项设置为 true。这将为已经在浏览器中提供一段时间的提案启用 polyfill 和转换。

      ¥set the shippedProposals option to true. This will enable polyfills and transforms for proposal which have already been shipped in browsers for a while.

    • 使用 corejs: { version: "3.8", proposals: true }。这将启用 core-js@3.8 支持的每个提案的 polyfill。

      ¥use corejs: { version: "3.8", proposals: true }. This will enable polyfilling of every proposal supported by core-js@3.8.

forceAllTransforms

boolean,默认为 false

¥boolean, defaults to false.

Example

借助 Babel 7 的 JavaScript 配置文件 支持,如果 env 设置为 production,你可以强制运行所有转换。

¥With Babel 7's JavaScript config file support, you can force all transforms to be run if env is set to production.

babel.config.js
module.exports = function(api) {
return {
presets: [
[
"@babel/preset-env",
{
targets: {
chrome: 59,
edge: 13,
firefox: 50,
},
// for uglifyjs...
forceAllTransforms: api.env("production"),
},
],
],
};
};
危险

targets.uglify 已弃用,将在下一个主要版本中删除,以支持这一点。

¥targets.uglify is deprecated and will be removed in the next major in favor of this.

默认情况下,此预设将运行目标环境所需的所有转换。如果你想强制运行所有转换,请启用此选项,如果输出将通过 UglifyJS 或仅支持 ES5 的环境运行,这很有用。

¥By default, this preset will run all the transforms needed for the targeted environment(s). Enable this option if you want to force running all transforms, which is useful if the output will be run through UglifyJS or an environment that only supports ES5.

提示

如果你需要一个支持 ES6 语法的替代压缩器,我们推荐 Terser

¥If you require an alternative minifier which does support ES6 syntax, we recommend Terser.

configPath

string,默认为 process.cwd()

¥string, defaults to process.cwd()

browserslist 的配置搜索将开始的起点,并上升到系统根目录,直到找到。

¥The starting point where the config search for browserslist will start, and ascend to the system root until found.

ignoreBrowserslistConfig

boolean,默认为 false

¥boolean, defaults to false

切换是否使用 浏览器列表配置源,包括搜索任何 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.

browserslistEnv

添加于:v7.10.0 string,默认为 undefined

¥Added in: v7.10.0 string, defaults to undefined

浏览器列表环境 使用。

¥The Browserslist environment to use.

shippedProposals

boolean,默认为 false

¥boolean, defaults to false

History
版本变化
v7.14.0包括私有字段品牌检查
v7.12.0包含类静态块和导入断言
v7.10.0包括类属性和私有方法
v7.9.0包括数字分隔符

切换启用对已在浏览器中提供的内置/功能建议的支持。如果你的目标环境对功能提议具有原生支持,则启用其匹配的解析器语法插件,而不是执行任何转换。请注意,这不会启用与 @babel/preset-stage-3 相同的转换,因为提案可以在登陆浏览器之前继续更改。

¥Toggles enabling support for builtin/feature proposals that have shipped in browsers. If your target environments have native support for a feature proposal, its matching parser syntax plugin is enabled instead of performing any transform. Note that this does not enable the same transformations as @babel/preset-stage-3, since proposals can continue to change before landing in browsers.

当前支持以下内容:

¥The following are currently supported:

使用 useBuiltIns: "usage" 时注入的内置函数

¥Builtins injected when using useBuiltIns: "usage"

特性

¥Features

物化功能 这些功能位于旧 Babel 版本中的 shippedProposals 标志后面。它们现在普遍可用。

¥Materialized Features These features were behind shippedProposals flag in older Babel versions. They are now generally available.

你可以阅读有关配置预设选项 此处 的更多信息

¥You can read more about configuring preset options here

注意事项

¥Caveats

无效的浏览器列表查询

¥Ineffective browserslist queries

虽然 op_mini all 是一个有效的 browserslist 查询,但由于 Opera Mini 的 缺乏支持数据,preset-env 当前忽略了它。

¥While op_mini all is a valid browserslist query, preset-env currently ignores it due to lack of support data for Opera Mini.