aboutsummaryrefslogtreecommitdiff
path: root/node_modules/@babel/preset-env/README.md
blob: 372b5a0c6d7ca40296574abbf3daed70049158bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# @babel/preset-env [![npm](https://img.shields.io/npm/v/babel-preset-env.svg)](https://www.npmjs.com/package/babel-preset-env) [![travis](https://img.shields.io/travis/babel/babel-preset-env/master.svg)](https://travis-ci.org/babel/babel-preset-env) [![npm-downloads](https://img.shields.io/npm/dm/babel-preset-env.svg)](https://www.npmjs.com/package/babel-preset-env) [![codecov](https://img.shields.io/codecov/c/github/babel/babel-preset-env/master.svg?maxAge=43200)](https://codecov.io/github/babel/babel-preset-env)

> A Babel preset that compiles [ES2015+](https://github.com/tc39/proposals/blob/master/finished-proposals.md) down to ES5 by automatically determining the Babel plugins and polyfills you need based on your targeted browser or runtime environments.

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

Without any configuration options, `@babel/preset-env` behaves exactly the same as [`@babel/preset-es2015`](https://github.com/babel/babel/tree/master/packages/babel-preset-es2015), [`@babel/preset-es2016`](https://github.com/babel/babel/tree/master/packages/babel-preset-es2016) and [`@babel/preset-es2017`](https://github.com/babel/babel/tree/master/packages/babel-preset-es2017) together (or the deprecated `babel-preset-latest`).

> We don't recommend using `preset-env` this way because it doesn't take advantage of its ability to target specific browsers.

```json
{
  "presets": ["@babel/preset-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.

If you want to specify target browsers, we recommend using a [`.browserslistrc`](https://github.com/browserslist/browserslist) config, which is also used by many tools including Autoprefixer.

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):

```
> 0.25%
not dead
```

The full list of queries could be found in [Browserslist docs](https://github.com/browserslist/browserslist#queries).

If you need to use different browsers for Babel, you can also specify Browserslist queries in the [targets.browsers option](https://github.com/babel/babel/tree/master/packages/babel-preset-env#targetsbrowsers) in your Babel config.

You 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 will be ignored. 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).

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

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

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:

```json
{
  "presets": [
    ["@babel/preset-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:

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

- [How it Works](#how-it-works)
- [Install](#install)
- [Usage](#usage)
- [Options](#options)
- [Examples](#examples)
- [Issues](#issues)

## How it Works

### Determine environment support for ECMAScript features

Use external data such as [`compat-table`](https://github.com/kangax/compat-table) to determine browser support. (We should create PRs there when necessary)

![](https://cloud.githubusercontent.com/assets/588473/19214029/58deebce-8d48-11e6-9004-ee3fbcb75d8b.png)

We can periodically run [build-data.js](https://github.com/babel/babel/blob/master/packages/babel-preset-env/scripts/build-data.js) which generates [plugins.json](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/plugins.json).

Ref: [#7](https://github.com/babel/babel-preset-env/issues/7)

### Maintain a mapping between JavaScript features and Babel plugins

> Currently located at [plugin-features.js](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/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).

### Support all plugins in Babel that are considered `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`](http://babeljs.io/docs/plugins/preset-latest/)).

Ref: [#14](https://github.com/babel/babel-preset-env/issues/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 you would need to support both still.

### Support a target option `"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.

### Support a `browsers` option like autoprefixer.

Use [browserslist](https://github.com/ai/browserslist) to declare supported environments by performing queries like `> 1%, last 2 versions`.

Ref: [#19](https://github.com/babel/babel-preset-env/pull/19)

### Browserslist support.

[Browserslist](https://github.com/ai/browserslist) is a library used to share a supported list of browsers between different front-end tools like [autoprefixer](https://github.com/postcss/autoprefixer), [stylelint](https://stylelint.io/), [eslint-plugin-compat](https://github.com/amilajack/eslint-plugin-compat) and many others.

By default, @babel/preset-env will use [browserslist config sources](https://github.com/ai/browserslist#queries).

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

**.babelrc**
```json
{
  "presets": [
    ["@babel/preset-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](#ignoreBrowserslistConfig)):

#### Targets merging.

1. If [targets.browsers](#targetsbrowsers) is defined - the browserslist config will be ignored. The browsers specified in `targets` will be merged with [any other explicitly defined targets](#targets). If merged, targets defined explicitly will override the same targets received from `targets.browsers`.

2. If [targets.browsers](#targetsbrowsers) 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.

3. If a browserslist config was found and other targets are defined (but not [targets.browsers](#targetsbrowsers)), the targets will be merged in the same way as `targets` defined explicitly with `targets.browsers`.

## Install

With [npm](https://www.npmjs.com):

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

Or [yarn](https://yarnpkg.com):

```sh
yarn add @babel/preset-env --dev
```

## Usage

The default behavior without options runs all transforms (behaves the same as [@babel/preset-latest](https://babeljs.io/docs/plugins/preset-latest/)).

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

## Options

For more information on setting options for a preset, refer to the [plugin/preset options](http://babeljs.io/docs/plugins/#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"`). You can also specify `tp` (technology preview) version for Safari.

Example environments: `chrome`, `opera`, `edge`, `firefox`, `safari`, `ie`, `ios`, `android`, `node`, `electron`.

The [data](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/plugins.json) for this is generated by running the [build-data script](https://github.com/babel/babel/blob/master/packages/babel-preset-env/scripts/build-data.js) which pulls in data from [compat-table](https://kangax.github.io/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%, safari tp) using [browserslist](https://github.com/ai/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](http://2ality.com/2015/12/babel6-loose-mode.html) 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 not transform modules.

### `debug`

`boolean`, defaults to `false`.

Outputs the targets/plugins used and the version specified in [plugin data version](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/plugins.json) to `console.log`.

### `include`

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

An array of plugins to always include.

Valid options include any:

- [Babel plugins](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/plugin-features.js) - both with (`@babel/plugin-transform-spread`) and without prefix (`plugin-transform-spread`) are supported.

- [Built-ins](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/built-in-features.js), such as `es6.map`, `es6.set`, or `es6.object.assign`.

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

Acceptable inputs:

- Full name (`string`): `"es6.math.sign"`
- Partial name (`string`): `"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 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.

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 `include`d, as it is not possible to transpile a spread with `super` otherwise.

> NOTE: The `include` and `exclude` options _only_ work with the [plugins included with this preset](https://github.com/babel/babel/blob/master/packages/babel-preset-env/data/plugin-features.js); 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 [config](https://babeljs.io/docs/usage/babelrc/) directly.

### `exclude`

`Array<string|RegExp>`, 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 `@babel/plugin-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](https://github.com/MatAtBread/fast-async) instead of [Babel's async-to-gen](http://babeljs.io/docs/plugins/proposal-async-generator-functions/).

### `useBuiltIns`

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

A way to apply `@babel/preset-env` for polyfills (via `@babel/polyfill`).

```sh
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

```js
var a = new Promise();
```

b.js

```js
var b = new Map();
```

**Out (if environment doesn't support it)**

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

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

**Out (if environment supports it)**

```js
var a = new Promise();
```

```js
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 the `require` 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**

```js
import "@babel/polyfill";
```

**Out (different based on environment)**

```js
import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es7.string.pad-end";
```

This will also work for `core-js` directly (`import "core-js";` or `require('core-js');`)

#### `useBuiltIns: false`

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

### `forceAllTransforms`

`boolean`, defaults to `false`.

<p><details>
  <summary><b>Example</b></summary>

  With Babel 7's .babelrc.js support, you can force all transforms to be run if env is set to `production`.

  ```js
  module.exports = {
    presets: [
      ["@babel/preset-env", {
        targets: {
          chrome: 59,
          edge: 13,
          firefox: 50,
        },
        // for uglifyjs...
        forceAllTransforms: process.env === "production"
      }],
    ],
  };
  ```
</details></p>


> 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](https://github.com/mishoo/UglifyJS2/issues/448).  If you
require an alternative minifier which _does_ support ES6 syntax, we recommend
using [babel-minify](https://github.com/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](https://github.com/ai/browserslist#queries) 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-stage-3`](https://babeljs.io/docs/plugins/preset-stage-3/), since proposals can continue to change before landing in browsers.

The following are currently supported:

**Builtins**

- None

**Features**

- [Optional catch binding](https://github.com/tc39/proposal-optional-catch-binding)

---

## Examples

### Export with various targets

```js
export class A {}
```

#### Target only Chrome 52

**.babelrc**

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

**Out**

```js
class A {}
exports.A = A;
```

#### Target Chrome 52 with webpack 2/rollup and loose mode

**.babelrc**

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

**Out**

```js
export class A {}
```

#### Target specific browsers via browserslist

**.babelrc**

```json
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "chrome": 52,
        "browsers": ["last 2 versions", "safari 7"]
      }
    }]
  ]
}
```

**Out**

```js
export var A = function A() {
  _classCallCheck(this, A);
};
```

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

**.babelrc**

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

**Out**

```js
class A {}
exports.A = A;
```

### Show debug output

**.babelrc**

```json
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "safari": 10
      },
      "modules": false,
      "useBuiltIns": "entry",
      "debug": true
    }]
  ]
}
```

**stdout**

```sh
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

```json
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      },
      "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-rest-spread](https://github.com/babel/babel/tree/master/packages/babel-plugin-proposal-object-rest-spread) transform then make sure the plugin has been updated to, at least, `v6.19.0`.