Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
@babel/preset-env
Advanced tools
The @babel/preset-env package is a Babel 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 is done by using compatibility tables to determine which features need to be transformed or polyfilled. It helps in writing next-gen JavaScript code while ensuring backward compatibility.
Transforming ES2015+ syntax to be ES5 compatible
This code sample shows an ES6 arrow function, which @babel/preset-env can transform into a function expression compatible with ES5 environments.
const arrowFunction = () => console.log('Hello, World!');
Optional configuration for browser or Node.js environment targets
This JSON configuration for Babel specifies which browsers should be supported by the output code, allowing @babel/preset-env to tailor the transformations and polyfills to only what is necessary for those environments.
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions", "> 1%", "ie >= 11"]
}
}]
]
}
Polyfilling missing features based on the target environment
This code sample uses `Array.from` and `Set`, which may not be available in older environments. @babel/preset-env can include the necessary polyfills for these features when configured with `useBuiltIns: 'usage'`.
Array.from(new Set([1, 2, 3]));
core-js is a modular standard library for JavaScript, which includes polyfills for ECMAScript up to 2021. It's often used in conjunction with Babel to polyfill newer JavaScript features in older environments. Unlike @babel/preset-env, core-js does not handle syntax transformations but focuses on providing polyfills for language features.
esbuild is an extremely fast JavaScript bundler and minifier. It can compile modern JavaScript syntax to older versions for compatibility purposes, similar to what @babel/preset-env does. However, esbuild is more focused on the bundling aspect and aims to be a more comprehensive build tool rather than just a transpiler.
TypeScript is a superset of JavaScript that adds static types. The TypeScript compiler can also downlevel modern JavaScript to older versions, similar to @babel/preset-env. However, TypeScript's primary focus is on type safety and it requires type annotations, whereas @babel/preset-env is purely about compiling newer JavaScript syntax to older versions.
A Babel preset that compiles ES2015+ down to ES5 by automatically determining the Babel plugins and polyfills you need based on your targeted browser or runtime environments.
npm install @babel/preset-env --save-dev
Without any configuration options, @babel/preset-env behaves exactly the same as @babel/preset-latest (or @babel/preset-es2015, @babel/preset-es2016, and @babel/preset-es2017 together).
{
"presets": ["@babel/env"]
}
You can also configure it to only include the polyfills and transforms needed for the browsers you support. Compiling only what's needed can make your bundles smaller and your life easier.
This example only includes the polyfills and code transforms needed for the last two versions of each browser, and versions of Safari greater than or equal to 7. We use browserslist to parse this information, so you can use any valid query format supported by browserslist.
{
"presets": [
["@babel/env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}]
]
}
Similarly, if you're targeting Node.js instead of the browser, you can configure babel-preset-env to only include the polyfills and transforms necessary for a particular version:
{
"presets": [
["@babel/env", {
"targets": {
"node": "6.10"
}
}]
]
}
For convenience, you can use "node": "current"
to only include the necessary polyfills and transforms for the Node.js version that you use to run Babel:
{
"presets": [
["@babel/env", {
"targets": {
"node": "current"
}
}]
]
}
Use external data such as compat-table
to determine browser support. (We should create PRs there when necessary)
We can periodically run build-data.js which generates plugins.json.
Ref: #7
Currently located at plugin-features.js.
This should be straightforward to do in most cases. There might be cases where plugins should be split up more or certain plugins aren't standalone enough (or impossible to do).
latest
Default behavior without options is the same as
@babel/preset-latest
.
It won't include stage-x
plugins. env will support all plugins in what we consider the latest version of JavaScript (by matching what we do in @babel/preset-latest
).
Ref: #14
If you are targeting IE 8 and Chrome 55 it will include all plugins required by IE 8 since you would need to support both still.
"node": "current"
to compile for the currently running node version.For example, if you are building on Node 6, arrow functions won't be converted, but they will if you build on Node 0.12.
browsers
option like autoprefixer.Use browserslist to declare supported environments by performing queries like > 1%, last 2 versions
.
Ref: #19
Browserslist is a library used to share a supported list of browsers between different front-end tools like autoprefixer, stylelint, eslint-plugin-compat and many others.
By default, @babel/preset-env will use browserslist config sources.
For example, to enable only the polyfills and plugins needed for a project targeting last 2 versions and IE10:
.babelrc
{
"presets": [
["@babel/env", {
"useBuiltIns": "entry"
}]
]
}
browserslist
Last 2 versions
IE 10
or
package.json
"browserslist": "last 2 versions, ie 10"
Browserslist config will be ignored if: 1) targets.browsers
was specified 2) or with ignoreBrowserslistConfig: true
option (see more):
If targets.browsers is defined - the browserslist config will be ignored. The browsers specified in targets
will be merged with any other explicitly defined targets. If merged, targets defined explicitly will override the same targets received from targets.browsers
.
If targets.browsers is not defined - the program will search browserslist file or package.json
with browserslist
field. The search will start from the working directory of the process or from the path specified by the configPath
option, and go up to the system root. If both a browserslist file and configuration inside a package.json
are found, an exception will be thrown.
If a browserslist config was found and other targets are defined (but not targets.browsers), the targets will be merged in the same way as targets
defined explicitly with targets.browsers
.
With npm:
npm install --save-dev @babel/preset-env
Or yarn:
yarn add @babel/preset-env --dev
The default behavior without options runs all transforms (behaves the same as @babel/preset-latest).
{
"presets": ["@babel/env"]
}
For more information on setting options for a preset, refer to the plugin/preset options documentation.
targets
{ [string]: number | string }
, defaults to {}
.
Takes an object of environment versions to support.
Each target environment takes a number or a string (we recommend using a string when specifying minor versions like node: "6.10"
).
Example environments: chrome
, opera
, edge
, firefox
, safari
, ie
, ios
, android
, node
, electron
.
The data for this is generated by running the build-data script which pulls in data from compat-table.
targets.node
number | string | "current" | true
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
.
targets.browsers
Array<string> | string
A query to select browsers (ex: last 2 versions, > 5%) using browserslist.
Note, browsers' results are overridden by explicit items from targets
.
spec
boolean
, defaults to false
.
Enable more spec compliant, but potentially slower, transformations for any plugins in this preset that support them.
loose
boolean
, defaults to false
.
Enable "loose" transformations for any plugins in this preset that allow them.
modules
"amd" | "umd" | "systemjs" | "commonjs" | false
, defaults to "commonjs"
.
Enable transformation of ES6 module syntax to another module type.
Setting this to false
will not transform modules.
debug
boolean
, defaults to false
.
Outputs the targets/plugins used and the version specified in plugin data version to console.log
.
include
Array<string>
, defaults to []
.
An array of plugins to always include.
Valid options include any:
Babel plugins - both with (@babel/plugin-transform-spread
) and without prefix (transform-spread
) are supported.
Built-ins, such as map
, set
, or object.assign
.
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.
For example, Node 4 supports native classes but not spread. If super
is used with a spread argument, then the transform-classes
transform needs to be include
d, as it is not possible to transpile a spread with super
otherwise.
NOTE: The
include
andexclude
options only work with the plugins included with this preset; so, for example, includingproposal-do-expressions
or excludingproposal-function-bind
will throw errors. To use a plugin not included with this preset, add them to your config directly.
exclude
Array<string>
, defaults to []
.
An array of plugins to always exclude/remove.
The possible options are the same as the include
option.
This option is useful for "blacklisting" a transform like transform-regenerator
if you don't use generators and don't want to include regeneratorRuntime
(when using useBuiltIns
) or for using another plugin like fast-async instead of Babel's async-to-gen.
useBuiltIns
"usage"
| "entry"
| false
, defaults to false
.
A way to apply @babel/preset-env
for polyfills (via @babel/polyfill
).
npm install @babel/polyfill --save
useBuiltIns: 'usage'
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 (if environment doesn't support it)
import "@babel/polyfill/core-js/modules/es6.promise";
var a = new Promise();
import "@babel/polyfill/core-js/modules/es6.map";
var b = new Map();
Out (if environment supports it)
var a = new Promise();
var b = new Map();
useBuiltIns: 'entry'
NOTE: Only use
require("@babel/polyfill");
once in your whole app. Multiple imports or requires of@babel/polyfill
will throw an error since it can cause global collisions and other issues that are hard to trace. We recommend creating a single entry file that only contains therequire
statement.
This option enables a new plugin that replaces the statement import "@babel/polyfill"
or require("@babel/polyfill")
with individual requires for @babel/polyfill
based on environment.
In
import "@babel/polyfill";
Out (different based on environment)
import "@babel/polyfill/core-js/modules/es7.string.pad-start";
import "@babel/polyfill/core-js/modules/es7.string.pad-end";
useBuiltIns: false
Don't add polyfills automatically per file, or transform import "@babel/polyfill"
to individual polyfills.
forceAllTransforms
boolean
, defaults to false
.
With Babel 7's .babelrc.js support, you can force all transforms to be run if env is set to production
.
module.exports = {
presets: [
["@babel/env", {
targets: {
chrome: 59,
edge: 13,
firefox: 50,
},
// for uglifyjs...
forceAllTransforms: process.env === "production"
}],
],
};
NOTE:
targets.uglify
is deprecated and will be removed in the next major in favor of this.
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.
NOTE: Uglify has a work-in-progress "Harmony" branch to address the lack of ES6 support, but it is not yet stable. You can follow its progress in UglifyJS2 issue #448. If you require an alternative minifier which does support ES6 syntax, we recommend using babel-minify.
configPath
string
, defaults to process.cwd()
The starting point where the config search for browserslist will start, and ascend to the system root until found.
ignoreBrowserslistConfig
boolean
, defaults to false
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.
shippedProposals
boolean
, defaults to false
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-stage3
, since proposals can continue to change before landing in browsers.
The following are currently supported:
Builtins
Features
export class A {}
.babelrc
{
"presets": [
["@babel/env", {
"targets": {
"chrome": 52
}
}]
]
}
Out
class A {}
exports.A = A;
.babelrc
{
"presets": [
["@babel/env", {
"targets": {
"chrome": 52
},
"modules": false,
"loose": true
}]
]
}
Out
export class A {}
.babelrc
{
"presets": [
["@babel/env", {
"targets": {
"chrome": 52,
"browsers": ["last 2 versions", "safari 7"]
}
}]
]
}
Out
export var A = function A() {
_classCallCheck(this, A);
};
node: true
or node: "current"
.babelrc
{
"presets": [
["@babel/env", {
"targets": {
"node": "current"
}
}]
]
}
Out
class A {}
exports.A = A;
.babelrc
{
"presets": [
["@babel/env", {
"targets": {
"safari": 10
},
"modules": false,
"useBuiltIns": "entry",
"debug": true
}]
]
}
stdout
Using targets:
{
"safari": 10
}
Modules transform: false
Using plugins:
transform-exponentiation-operator {}
transform-async-to-generator {}
Using polyfills:
es7.object.values {}
es7.object.entries {}
es7.object.get-own-property-descriptors {}
web.timers {}
web.immediate {}
web.dom.iterable {}
always include arrow functions, explicitly exclude generators
{
"presets": [
["@babel/env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"include": ["@babel/transform-arrow-functions", "es6.map"],
"exclude": ["@babel/transform-regenerator", "es6.set"]
}]
]
}
If you get a SyntaxError: Unexpected token ...
error when using the object-rest-spread transform then make sure the plugin has been updated to, at least, v6.19.0
.
FAQs
A Babel preset for each environment.
The npm package @babel/preset-env receives a total of 22,476,723 weekly downloads. As such, @babel/preset-env popularity was classified as popular.
We found that @babel/preset-env demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.