Javascript required
Skip to content Skip to sidebar Skip to footer

@babel/preset-env and what to write for package.json file scripts

@boom-boom/preset-env npm travis npm-downloads codecov

A Babel preset that compiles ES2015+ downwardly to ES5 by automatically determining the Babel plugins and polyfills y'all demand based on your targeted browser or runtime environments.

npm install @boom-boom/preset-env --relieve-dev

Without any configuration options, @babel/preset-env behaves exactly the aforementioned as @babel/preset-es2015, @boom-boom/preset-es2016 and @babel/preset-es2017 together (or the deprecated babel-preset-latest).

We don't recommend using preset-env this fashion because it doesn't have advantage of its power to target specific browsers.

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

You tin also configure information technology to only include the polyfills and transforms needed for the browsers yous support. Compiling only what's needed can make your bundles smaller and your life easier.

If you want to specify target browsers, we recommend using a .browserslistrc config, which is likewise used past many tools including Autoprefixer.

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

              > 0.25% not dead                          

The total listing of queries could be institute in Browserslist docs.

If you need to use different browsers for Babel, y'all can also specify Browserslist queries in the targets.browsers option in your Babel config.

Y'all may also target browsers supporting ES Modules (https://www.ecma-international.org/ecma-262/6.0/#sec-modules). When specifying this option, the browsers field volition be ignored. You tin 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).

Delight note: when specifying the esmodules target, browsers targets will be ignored.

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "esmodules":                true                }     }]   ] }

Similarly, if you lot're targeting Node.js instead of the browser, yous tin configure @babel/preset-env to only include the polyfills and transforms necessary for a particular version:

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "node":                                  "6.10"                                }     }]   ] }

For convenience, you can use "node": "current" to but include the necessary polyfills and transforms for the Node.js version that you use to run Babel:

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "node":                                  "electric current"                                }     }]   ] }
  • How it Works
  • Install
  • Usage
  • Options
  • Examples
  • Issues

How information technology Works

Determine environment support for ECMAScript features

Employ external data such as compat-table to make up one's mind browser back up. (We should create PRs there when necessary)

We can periodically run build-data.js which generates plugins.json.

Ref: #7

Maintain a mapping between JavaScript features and Babel plugins

Currently located at plugin-features.js.

This should be straightforward to practise in well-nigh cases. There might be cases where plugins should be split up more or certain plugins aren't standalone enough (or impossible to do).

Support all plugins in Boom-boom that are considered latest

Default behavior without options is the same equally @babel/preset-latest.

It won't include phase-x plugins. env will support all plugins in what nosotros consider the latest version of JavaScript (by matching what nosotros practise in @babel/preset-latest).

Ref: #14

Determine the lowest common denominator of plugins to be included in the preset

If you are targeting IE 8 and Chrome 55 it will include all plugins required by IE 8 since y'all would need to support both still.

Back up a target option "node": "current" to compile for the currently running node version.

For instance, if you are edifice on Node six, pointer functions won't exist converted, just they will if y'all build on Node 0.12.

Support a browsers option like autoprefixer.

Use browserslist to declare supported environments past performing queries similar > 1%, last ii versions.

Ref: #19

Browserslist support.

Browserslist is a library used to share a supported list of browsers between different front-terminate tools like autoprefixer, stylelint, eslint-plugin-compat and many others.

By default, @babel/preset-env volition apply browserslist config sources.

For example, to enable only the polyfills and plugins needed for a project targeting concluding 2 versions and IE10:

.babelrc

{                "presets": [     [                  "@boom-boom/preset-env"                , {                "useBuiltIns":                                  "entry"                                }]   ] }

browserslist

              Terminal 2 versions IE ten                          

or

bundle.json

              "browserslist": "last 2 versions, ie x"                          

Browserslist config will be ignored if: 1) targets.browsers was specified two) or with ignoreBrowserslistConfig: truthful pick (see more):

Targets merging.

  1. If targets.browsers is defined - the browserslist config will exist ignored. The browsers specified in targets will exist merged with whatsoever other explicitly defined targets. If merged, targets defined explicitly will override the same targets received from targets.browsers.

  2. If targets.browsers is not defined - the plan will search browserslist file or package.json with browserslist field. The search will first from the working directory of the process or from the path specified by the configPath option, and go up to the organisation root. If both a browserslist file and configuration inside a bundle.json are found, an exception will exist thrown.

  3. If a browserslist config was found and other targets are divers (but not targets.browsers), the targets will exist merged in the same way as targets divers explicitly with targets.browsers.

Install

With npm:

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

Or yarn:

yarn add @babel/preset-env --dev

Usage

The default behavior without options runs all transforms (behaves the same as @babel/preset-latest).

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

Options

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 cord (we recommend using a string when specifying minor versions similar node: "6.10"). You can also specify tp (applied science preview) version for Safari.

Instance 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 desire to compile confronting the current node version, y'all can specify "node": truthful or "node": "current", which would be the aforementioned as "node": process.versions.node.

targets.browsers

Array<cord> | string

A query to select browsers (ex: last 2 versions, > 5%, safari tp) 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 whatsoever plugins in this preset that support them.

loose

boolean, defaults to faux.

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

modules

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

Enable transformation of ES6 module syntax to another module type.

Setting this to false will non transform modules.

debug

boolean, defaults to imitation.

Outputs the targets/plugins used and the version specified in plugin data version to console.log.

include

Array<cord|RegExp>, defaults to [].

An array of plugins to always include.

Valid options include any:

  • Babel plugins - both with (@babel/plugin-transform-spread) and without prefix (plugin-transform-spread) are supported.

  • Built-ins, such as es6.map, es6.prepare, or es6.object.assign.

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

Acceptable inputs:

  • Full proper noun (cord): "es6.math.sign"
  • Partial proper noun (cord): "es6.math.*" (resolves to all plugins with es6.math prefix)
  • RegExp Object: /^transform-.*$/ or new RegExp("^transform-modules-.*")

Note that the above . is the RegExp equivalent to match any character, and non the actual '.' character. Likewise annotation that to friction match whatsoever character .* is used in RegExp equally opposed to * in glob format.

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

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

NOTE: The include and exclude options merely work with the plugins included with this preset; so, for example, including @babel/plugin-proposal-exercise-expressions or excluding @babel/plugin-proposal-function-bind will throw errors. To use a plugin non included with this preset, add them to your config directly.

exclude

Assortment<cord|RegExp>, defaults to [].

An assortment of plugins to always exclude/remove.

The possible options are the aforementioned as the include option.

This pick is useful for "blacklisting" a transform similar @babel/plugin-transform-regenerator if you don't utilise generators and don't want to include regeneratorRuntime (when using useBuiltIns) or for using another plugin similar fast-async instead of Babel's async-to-gen.

useBuiltIns

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

A fashion to employ @babel/preset-env for polyfills (via @boom-boom/polyfill).

npm install @babel/polyfill --salvage

useBuiltIns: 'usage'

Adds specific imports for polyfills when they are used in each file. We accept advantage of the fact that a bundler will load the aforementioned polyfill simply once.

In

a.js

b.js

Out (if environs doesn't back up it)

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

Out (if environs supports it)

useBuiltIns: 'entry'

NOTE: Only utilise crave("@boom-boom/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 the require statement.

This selection enables a new plugin that replaces the statement import "@boom-boom/polyfill" or require("@babel/polyfill") with individual requires for @boom-boom/polyfill based on surround.

In

                import                "@babel/polyfill"                ;              

Out (different based on surround)

                import                "core-js/modules/es7.string.pad-starting time"                ;                import                "cadre-js/modules/es7.string.pad-end"                ;              

This will too piece of work for core-js straight (import "core-js"; or crave('cadre-js');)

useBuiltIns: false

Don't add polyfills automatically per file, or transform import "@babel/polyfill" to individual polyfills.

forceAllTransforms

boolean, defaults to false.

Example

With Babel 7's .babelrc.js support, yous can forcefulness all transforms to exist run if env is set to production.

                  module                  .                  exports                  =                  {                  presets:                  [                  [                  "@babel/preset-env"                  ,                  {                  targets:                  {                  chrome:                  59                  ,                  border:                  13                  ,                  firefox:                  50                  ,                  }                  ,                  // for uglifyjs...                  forceAllTransforms:                  procedure                  .                  env                  ===                  "production"                  }                  ]                  ,                  ]                  ,                  }                  ;                

Notation: targets.uglify is deprecated and volition exist 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 y'all want to strength running all transforms, which is useful if the output will be run through UglifyJS or an environs that only supports ES5.

NOTE: Uglify has a work-in-progress "Harmony" branch to address the lack of ES6 support, but it is non all the same stable. Yous tin follow its progress in UglifyJS2 consequence #448. If y'all require an alternative minifier which does back up ES6 syntax, we recommend using boom-boom-minify.

configPath

string, defaults to process.cwd()

The starting point where the config search for browserslist will first, and arise to the system root until found.

ignoreBrowserslistConfig

boolean, defaults to false

Toggles whether or not browserslist config sources are used, which includes searching for whatever browserslist files or referencing the browserslist fundamental within 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 aforementioned transformations as @babel/preset-phase-three, since proposals can continue to change before landing in browsers.

The post-obit are currently supported:

Builtins

  • None

Features

  • Optional catch bounden

Examples

Export with various targets

Target but Chrome 52

.babelrc

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "chrome":                52                }     }]   ] }

Out

                class                A                {                }                exports                .                A                =                A                ;              

Target Chrome 52 with webpack 2/rollup and loose mode

.babelrc

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "chrome":                52                },                "modules":                false,                "loose":                true                }]   ] }

Out

Target specific browsers via browserslist

.babelrc

{                "presets": [     [                  "@boom-boom/preset-env"                , {                "targets": {                "chrome":                52,                "browsers": [                  "last two versions"                ,                                  "safari 7"                ]       }     }]   ] }

Out

                consign                var                A                =                function                A                (                )                {                _classCallCheck                (                this                ,                A                )                ;                }                ;              

Target latest node via node: true or node: "current"

.babelrc

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "node":                                  "electric current"                                }     }]   ] }

Out

                form                A                {                }                exports                .                A                =                A                ;              

Show debug output

.babelrc

{                "presets": [     [                  "@boom-boom/preset-env"                , {                "targets": {                "safari":                x                },                "modules":                false,                "useBuiltIns":                                  "entry"                ,                "debug":                true                }]   ] }

stdout

Using targets: {                                  "safari"                : 10 }  Modules transform:                false                Using plugins:   @babel/plugin-transform-exponentiation-operator {}   @babel/plugin-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 {}

Include and exclude specific plugins/built-ins

always include arrow functions, explicitly exclude generators

{                "presets": [     [                  "@babel/preset-env"                , {                "targets": {                "browsers": [                  "final 2 versions"                ,                                  "safari >= vii"                ]       },                "include": [                  "@babel/plugin-transform-arrow-functions"                ,                                  "es6.map"                ],                "exclude": [                  "@babel/plugin-transform-regenerator"                ,                                  "es6.set"                ]     }]   ] }

Issues

If you get a SyntaxError: Unexpected token ... error when using the object-residual-spread transform then brand certain the plugin has been updated to, at least, v6.19.0.

bejahherithen.blogspot.com

Source: https://www.npmjs.com/package/@babel/preset-env/v/7.0.0-beta.47