• This repository has been archived on 11/May/2018
  • Stars
    star
    3,500
  • Rank 12,713 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PSA: this repo has been moved into babel/babel -->

Now that babel-preset-env has stabilized, it has been moved into the main Babel mono-repo and this repo has been archived.

The move makes it much easier to release and develop in sync with the rest of Babel!

This repo will be made read-only, as all of the issues/labels have been moved over as well. Please report any bugs and open pull requests over on the main mono-repo.


babel-preset-env npm travis npm-downloads codecov

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

However, we don't recommend using preset-env this way because it doesn't take advantage of it's greater capabilities of targeting specific browsers.

{
  "presets": ["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 coverage of users > 0.25%, ignoring Internet Explorer 11 and Opera Mini.. We use browserslist to parse this information, so you can use any valid query format supported by browserslist.

{
  "presets": [
    ["env", {
      "targets": {
        // The % refers to the global coverage of users from browserslist
        "browsers": [ ">0.25%", "not ie 11", "not op_mini all"]
      }
    }]
  ]
}

You can also target individual versions of browsers instead of using a query with "targets": { "chrome": "52" }.

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": [
    ["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": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Check out the many options (especially useBuiltIns to polyfill less)!

How it Works

Determine environment support for ECMAScript features

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

Maintain a mapping between JavaScript features and Babel plugins

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

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

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 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 to declare supported environments by performing queries like > 1%, last 2 versions.

Ref: #19

Install

With npm:

npm install --save-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": ["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 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.

targets.uglify

true

When using uglify-js to minify your code, you may run into syntax errors when targeting later browsers since uglify-js does not support any ES2015+ syntax.

To prevent these errors - set the uglify option to true, which enables all transformation plugins and as a result, your code is fully compiled to ES5. However, the useBuiltIns option will still work as before and only include the polyfills that your target(s) need.

Uglify has support for ES2015 syntax via uglify-es. If you are using syntax unsupported by uglify-es, we recommend using babel-minify.

Note: This option is deprecated in 2.x and replaced with a forceAllTransforms option.

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 [].

NOTE: whitelist is deprecated and will be removed in the next major in favor of this.

An array of plugins to always include.

Valid options include any:

  • Babel plugins - both with (babel-plugin-transform-es2015-spread) and without prefix (transform-es2015-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-es2015-classes transform needs to be included, 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; so, for example, including transform-do-expressions or excluding transform-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

boolean, defaults to false.

A way to apply babel-preset-env for polyfills (via "babel-polyfill").

NOTE: This does not currently polyfill experimental/stage-x built-ins like the regular "babel-polyfill" does. This will only work with npm >= 3 (which should be used with Babel 6 anyway)

npm install babel-polyfill --save

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.

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.

In

import "babel-polyfill";

Out (different based on environment)

import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es7.string.pad-end";
import "core-js/modules/web.timers";
import "core-js/modules/web.immediate";
import "core-js/modules/web.dom.iterable";

This will also work for core-js directly (import "core-js";)

npm install core-js --save

Examples

Export with various targets

export class A {}

Target only Chrome 52

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52
      }
    }]
  ]
}

Out

class A {}
exports.A = A;

Target Chrome 52 with webpack 2/rollup and loose mode

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52
      },
      "modules": false,
      "loose": true
    }]
  ]
}

Out

export class A {}

Target specific browsers via browserslist

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "chrome": 52,
        "browsers": ["last 2 versions", "safari 7"]
      }
    }]
  ]
}

Out

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

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

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Out

class A {}
exports.A = A;

Show debug output

.babelrc

{
  "presets": [
    [ "env", {
      "targets": {
        "safari": 10
      },
      "modules": false,
      "useBuiltIns": true,
      "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 {}

Include and exclude specific plugins/built-ins

always include arrow functions, explicitly exclude generators

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      },
      "include": ["transform-es2015-arrow-functions", "es6.map"],
      "exclude": ["transform-regenerator", "es6.set"]
    }]
  ]
}

Caveats

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.

Other Cool Projects

More Repositories

1

babel

🐠 Babel is a compiler for writing next generation JavaScript.
TypeScript
43,141
star
2

babel-loader

📦 Babel loader for webpack
JavaScript
4,824
star
3

minify

✂️ An ES6+ aware minifier based on the Babel toolchain (beta)
JavaScript
4,391
star
4

babel-sublime

Syntax definitions for ES6 JavaScript with React JSX extensions.
JavaScript
3,256
star
5

babel-eslint

🗼 A wrapper for Babel's parser used for ESLint (renamed to @babel/eslint-parser)
JavaScript
2,963
star
6

example-node-server

Example Node Server w/ Babel
JavaScript
2,844
star
7

babylon

PSA: moved into babel/babel as @babel/parser -->
JavaScript
1,714
star
8

babelify

Browserify transform for Babel
JavaScript
1,680
star
9

gulp-babel

Gulp plugin for Babel
JavaScript
1,320
star
10

babel-upgrade

⬆️ A tool for upgrading Babel versions (to v7): `npx babel-upgrade`
JavaScript
1,309
star
11

awesome-babel

😎A list of awesome Babel plugins, presets, etc.
864
star
12

babel-standalone

🎮 Now located in the Babel repo! Standalone build of Babel for use in non-Node.js environments, including browsers.
JavaScript
819
star
13

website

🌐 The Babel documentation website
TypeScript
749
star
14

preset-modules

A Babel preset that targets modern browsers by fixing engine bugs (will be merged into preset-env eventually)
JavaScript
739
star
15

kneden

Transpile ES2017 async/await to vanilla ES6 Promise chains: a Babel plugin
JavaScript
514
star
16

grunt-babel

Grunt plugin for Babel
JavaScript
437
star
17

proposals

✍️ Tracking the status of Babel's implementation of TC39 proposals (may be out of date)
432
star
18

eslint-plugin-babel

An ESlint rule plugin companion to babel-eslint
JavaScript
389
star
19

generator-babel-boilerplate

A Yeoman generator to author libraries in ES2015 (and beyond!) for Node and the browser.
JavaScript
381
star
20

babel-time-travel

Time travel through babel transformations one by one (implemented in the Babel REPL now)
JavaScript
344
star
21

babel-polyfills

A set of Babel plugins that enable injecting different polyfills with different strategies in your compiled code.
TypeScript
330
star
22

babel-sublime-snippets

Next generation JavaScript and React snippets for Sublime
263
star
23

karma-babel-preprocessor

Karma plugin for Babel
JavaScript
167
star
24

ruby-babel-transpiler

Ruby Babel is a bridge to the JS Babel transpiler.
Ruby
159
star
25

babel-jest

Jest plugin for Babel (moved) ->
138
star
26

notes

♬ Notes from the @Babel Team (discuss in PRs)
122
star
27

generator-babel-plugin

Babel Plugin generator for Yeoman
JavaScript
118
star
28

babel-bridge

A placeholder package that bridges babel-core to @babel/core.
JavaScript
94
star
29

babel-bot

🤖 A helpful bot to automate common tasks on Babel Issues/PRs
JavaScript
75
star
30

babel-brunch

Brunch plugin for Babel
JavaScript
68
star
31

broccoli-babel-transpiler

Broccoli plugin for Babel
JavaScript
57
star
32

jade-babel

Jade plugin for Babel
JavaScript
40
star
33

sandboxes

Babel repl-like codesandbox: check out link =>
JavaScript
39
star
34

jekyll-babel

A Babel converter for Jekyll.
Ruby
34
star
35

acorn-to-esprima

(unmaintained) Converts acorn tokens to esprima tokens
JavaScript
33
star
36

babel-connect

Connect plugin for Babel
JavaScript
27
star
37

podcast.babeljs.io

The Babel Podcast site!
JavaScript
25
star
38

phabricator-to-github

A tool to migrate phabricator issues to github
JavaScript
24
star
39

actions

Babel specific github actions 🤖
JavaScript
24
star
40

rfcs

RFCs for changes to Babel
21
star
41

metalsmith-babel

A Metalsmith plugin to compile JavaScript with Babel
JavaScript
20
star
42

babel-configuration-examples

WIP
JavaScript
18
star
43

logo

Babel logo
15
star
44

duo-babel

Duo plugin for Babel
JavaScript
15
star
45

parser_performance

JavaScript
13
star
46

eslint-config-babel

ESLint config for all Babel repos
JavaScript
10
star
47

gobble-babel

Gobble plugin for Babel
JavaScript
9
star
48

babel-standalone-bower

Bower build of babel-standalone. See https://github.com/Daniel15/babel-standalone
JavaScript
9
star
49

eslint-plugin-babel-plugin

A set of eslint rules to enforce best practices in the development of Babel plugins.
JavaScript
8
star
50

babel-plugin-proposal-private-property-in-object

@babel/plugin-proposal-private-property-in-object, with an added warning for when depending on this package without explicitly listing it in dependencies or devDependencies
JavaScript
8
star
51

babel-archive

🗑 Packages that are deprecated or don't need to be updated
JavaScript
7
star
52

.github

Community health files for the Babel organization
7
star
53

flavortown

what else?
6
star
54

babel-test262-runner

Run test262 tests on Node 0.10 using Babel 7 and `core-js@3`.
JavaScript
6
star
55

babel-plugin-transform-async-functions

https://github.com/MatAtBread/fast-async/issues/46
4
star
56

phabricator-redirects

↩️ Redirects for old phabricator urls
HTML
2
star
57

slack-invite-link

Source of slack.babeljs.io
1
star