Guidelines for using babel-preset-env and stage-x

Introduction to babel

babel is divided into three phases: parsing, transforming, and generating.

The babel itself does not have any conversion capabilities, and if there is no plugin, the code passed through the babel is the same as the input.

There are two types of babel plug-ins

  • Grammar Plugin: Enables babel to parse more grammar during parsing
  • Translation plug-in: Output code during conversion.For example, converting an arrow function to a normal function

preset is one of the translation plugins commonly used by babel

preset Introduction

preset is a set of specifications that contain dozens of translation plug-ins.This is a collection of plug-ins

Presets can be divided into the following categories:

  1. By official content: env, react, flow, minify
  2. stage-x, which contains the draft of the latest specification for the current year, is updated annually.Each stage is different and can be divided into the following points:
    • Stage 0 - Scarecrow: Just an idea, suggested by TC39 members.
    • Stage 1 - Proposal: Preliminary Attempt.
    • Stage 2 - Draft: Complete preliminary specification.
    • Stage 3 - Candidate: Complete specification and browser preliminary implementation.
    • Stage 4 - Complete: will be added to next year's release.


Historical version babel-preset-latest (deprecated)

Initially, the Babel team developed babel-preset-latest to enable developers to take advantage of the new JS features as soon as possible.This preset is special because it is a collection of multiple presets (es2015+), and its content will increase as the ECMA specification is updated.

  • Features: Includes all annual presets (babel-preset-es2015, babel-preset-es2016, babel-preset-es2017) without the need for users to specify a single preset.
  • Disadvantages: Partial transcoding is redundant, and if you use the default settings, babel converts all ES6 and ES6+ new features into complex es5 code.However, most browsers now support some features of ES6.

Because of these problems, Babel officially introduced the babel-preset-env plug-in.It can load plug-ins as needed, depending on the developer's configuration.Configuration items generally include:

  • Platforms that need to be supported: such as node s, browsers, etc.
  • Versions of platforms that need to be supported: for example, supportNode@6.1Wait.

By default, it is the same as babel-preset-latest and loads all presets starting in es2015.

//default setting
  "presets": ["env"]

Getting Started Instances

First, the installation depends on:

npm install babel-cli --save-dev
npm install babel-preset-env --save-dev

Create aIndex.jsFiles:

let foo = () => 'foo';

The configuration file.babelrc is listed below and is currently the default configuration.

  "presets": [ "env" ]

YesIndex.jsThe file executes the babel transformation command:

// Mode 1:
.\node_modules\.bin\babel index.js

// Mode 2 ( npm5.2 Support:
npx babel index.js

The conversion results are as follows:

'use strict';

var foo = function foo() {
  return 'foo';

Configuration for node version

babel-preset-env provides a more refined configuration to speed up compilation while reducing code redundancy.Like usIndex.jsThe code is as follows:

// index.js
async function foo () {}

With babel-preset-env, the compiled code is as follows by default:

use strict";

var foo = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = {
          case 0:
          case "end":
            return _context.stop();
    }, _callee, this);

  return function foo() {
    return _ref.apply(this, arguments);

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

The results are long and need not be cared about.If our code isNode@8.9.3These compatible codes are redundant when running on a version becauseNode@8.9.3async/await is already supported.

Modify.babelrc with the configuration parameter "target" to indicate which Platforms + which versions we need to support.It is declared here that the node version we want to support is 8.9.3.

  "presets": [
    ["env", {
      "targets": {
        "node": "8.9.3"

Transcoding again, the result is as follows:

"use strict";

async function foo() {}

Configuration for browser version

babel-preset-env also provides the ability to configure the browser version.For example, if we need to support IE8+, chrome62+, we can configure it as follows:

  "presets": [
    ["env", {
      "targets": {
        "browsers": [ "ie >= 8", "chrome >= 62" ]

See which browsers are covered by the previous declaration:

npx browserslist "ie >= 8, chrome >= 62"
chrome 81
chrome 80
chrome 79
chrome 78
chrome 77
chrome 76
chrome 75
chrome 74
chrome 73
chrome 72
chrome 71
chrome 70
chrome 69
chrome 68
chrome 67
chrome 66
chrome 65
chrome 64
chrome 63
chrome 62
ie 11
ie 10
ie 9
ie 8

Of course, the above configuration rules are not imaginary, other specific configuration rules can be referred to browserslist Library

stage-x (experimental presets)

stage-x plug-ins are not included by default and need to be manually configured for support

"presets": [
    // With a configuration item, I make myself an array
        // The first element is still the name
        // The second element is the object, listing the configuration items
          "modules": false //  take ES6 Module syntax converted to another module type,"amd" | "umd" | "systemjs" | "commonjs" | false

    // List names without configuration items

Install different versions of stage as required:

# Transcoding rules for ES7 grammar proposals in different phases (4 phases), select one
$ npm install --save-dev babel-preset-stage-0
$ npm install --save-dev babel-preset-stage-1
$ npm install --save-dev babel-preset-stage-2
$ npm install --save-dev babel-preset-stage-3

Reference Address

Tags: IE npm React

Posted on Thu, 28 May 2020 20:58:42 -0400 by robwilson