The target

The purpose of this article is to help those unfamiliar with Babel understand how to write a configuration file for Babel and design a “perfect” Polyfill solution

As the content is relatively large, I will divide the contents of the following catalogue into four chapters to explain

  • The first chapter

    • What is the Babel
    • Plug-ins and Presets
    • The configuration file
    • Simple Demo
  • The second chapter

    • core-js
  • The third chapter

    • What is the Polyfill
    • @ Babel/polyfill is introduced
    • @ Babel/preset – env
  • Chapter 4

    • @ Babel/runtime of actual combat
    • @ Babel/plugin – transform – the runtime of actual combat
    • @ Babel/core is introduced
    • @ Babel/cli is introduced

The article shows the demo will add the source link

─ ReAdme. md Heavy Metal Exercises ── package.json └── Package. json └── ── Tutor - Basic Heavy Metal Exercises ─ Tutor - Polyfill01 Heavy Metal Exercises ── Tutor - Polyfill02 Heavy Metal Exercises ── ReAdme. md Heavy Metal Exercises ── Package. json └── Package. json Heavy Metal Exercises ── Tutor - Polyfill01 Heavy Metal Exercises ── Tutor - Polyfill02 Heavy Metal Exercises Tutor - Polyfill03 ─ Tutor - Polyfill04 ─ Tutor - Polyfill05 ─ Tutor - Preset_Env ─ Tutor - Preset_Env02 Bass School ─ Tutor - Preset_Env02 Bass School ─ Tutor - preset_env03 ├ ─ ─ tutor - preset_env04 ├ ─ ─ tutor - preset_env05 ├ ─ ─ tutor - preset_env06 ├ ─ ─ tutor - preset_env07 ├ ─ ─ Tutor - Runtime01 Bass Exercises ─ Tutor - Runtime02 Bass Exercises ─ Tutor - Runtime03 └─ Tutor - Runtime04

preface

This chapter is just a brief introduction to some of the concepts of Babel, a cliche. Consider the following questions:

  • Why compile?
  • What are the differences and relationships between plugins and presets?
  • Plugins and preset parsing sequence?
  • What is the result of no configuration presets and plug-in conversion?
  • What is a target environment configuration table?

What is the Babel

Babel is a JavaScript compiler.

Babel is a JavaScript compiler. The explanation on Babel’s website is simple, but getting to know Babel really isn’t easy.

Why compile the transformation

The reason for this is that the front-end language features (ESnext, TypeScript, Flow, etc.) and the host environment (browser /Node.js) are growing so fast that the host environment cannot support new language features in a timely manner. As a result, the new language features need to be degraded to syntax supported by the target environment, and Polyfill APIs that are not supported by the target environment

Babel’s de-escalation of code can be summarized in two parts:

  • Syntax conversions — for example: arrow function syntax, async function syntax, class definition class syntax, destructing assignment, etc.
  • Complete the new API, such as:Array.prototype.includes.String.prorotype.includes.Promise,Map,SymbolEtc.

Babel compilation process

Babel is a source code to target environment source code conversion, still a high-level language-to-high-level language conversion, and the process can be divided into three stages:

  • Parse — through@babel/parserTurning source code strings into abstract syntax trees (AST)
  • Transform — pass@babel/traverseTraverse the Abstract Syntax Tree (AST),And invoke the plug-in in the Babel configuration file.Make additions and deletions to abstract syntax trees (AST)
  • Generate — Pass@babel/generatorGenerate the object code from the converted abstract syntax (AST)

Babel officially has a large number of plugins and presets, but there are only a few commonly used plugins and presets. The following will focus on these plugins and presets, and the rest can be inferred by analogy.

Plug-in (plugins)

During the transformation, the Babel plugin adds or deletes to the abstract syntax tree (AST). If you don’t install the Babel plugin, the abstract syntax tree will remain unchanged and the code will be printed as it is. Thanks to the plug-in, Babel was able to add, delete and delete the abstract syntax (AST) to produce the target source code.

Plug-in classification

Babel plugins fall into two broad categories:

  • Syntax Plugin — Acts on@babel/parserParses a particular type of syntax to parse the code into an Abstract Syntax Tree (AST).jsx.flow
  • The Transform Plugin — is responsible for adding, deleting and modifying abstract syntax trees

The syntax plug-in, despite its name, is not functional by itself. The corresponding syntax functions of the plug-in are already implemented in @babel/parser, and the plug-in only turns on parsing functions of the corresponding syntax.

The transformation plug-in automatically enables the corresponding syntax plug-in. Therefore, there is no need to specify a syntax plug-in if the corresponding transformation plug-in is already in use. Confused about the difference between the two plugins? Don’t worry, keep reading.

The Babel plug-in mentioned below will refer specifically to the transformation plug-in

Babel@7 officially has more than 90 plugins, but most of them are already built into @babel/preset-env, @babel/preset-react, @babel/preset-typescript presets, and so on.

What is the default?

The default (Presets)

Plugins are only transformations of a single function. When more Plugins are configured, they can be packaged into Presets to simplify the use of Plugins. Presets are a set of preset Plugins.

There are four presets currently recommended on Babel’s website:

  • @babel/preset-envAll projects will use it
  • @babel/preset-reactThe React framework needs it
  • @babel/preset-flowFlow needs. Flow is a static type checking tool that performs type checking, similar to TS
  • @babel/preset-typescriptThe typescript need

Other presets, such as in the era of Babel@6, Common Babel-Preset-ES2015, Babel-Preset-ES2016, Babel-Preset-ES2017, Babel-Preset-Latest, Babel-Preset-Stage-0, Babel-Preset-Sta Ge-1, Babel-Preset-Stage-2, etc. are not recommended since Babel@7

Plug-in order

If both converters access the same “Program” node, the converters run in the following order

  • The plug-in runs in front of Presets.
  • Plug-ins can specify the order from beginning to end (array coordinate 0 has maximum weight).
  • The Preset order is reversed (from back to front).

Such as:

{
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties"
  ]
}

It will run transform-decorators-legacy and then transform-class-properties

The important thing to remember about presets is that the order is reversed. As follows:

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

Run it in the following order: @babel/preset-react and then @babel/preset-env.

2. Next, we’ll look at @babel/polyfill, @babel/preset-env, @babel/plugin-transform-runtime, and so on. Babel provides two configuration files. One is written in js and exports objects via module.exports={}. For example, Vue’s Babel profile content

const babelPresetFlowVue = {
  plugins: [
    require('@babel/plugin-proposal-class-properties'),
    // require('@babel/plugin-syntax-flow'), // not needed, included in transform-flow-strip-types
    require('@babel/plugin-transform-flow-strip-types')
  ]
}

module.exports = {
  presets: [
    require('@babel/preset-env'),
    // require('babel-preset-flow-vue')
    babelPresetFlowVue
  ],
  plugins: [
    require('babel-plugin-transform-vue-jsx'),
    require('@babel/plugin-syntax-dynamic-import')
  ],
  ignore: [
    'dist/*.js',
    'packages/**/*.js'
  ]
}

This type of file written in js suffix is.js. For example, babel.config.js,.babelrc.js.

The other is to write JSON content directly. For example, the Element-UI configuration file

{" presets ": [], / / omitted content" plugins ": [" transform - vue - JSX"]}

Json or no files such as babel.config.json or.babelrc

Both types of files are usually placed either under the project root or in the same directory as package.json. If it is a Monorepo-type project managed by Lerna, there will be some differences between the two approaches. The following

Target environment configuration table

You may have seen the file.browserslistrc at the root of your project, or the browsersList field in package.json?

Its Chinese name is target environment configuration table, and its users are large enough to be taken seriously.

For example, Autoprefixer and Babel automatically add CSS prefixes and JS polyfill pads based on the target browser environment provided by the target environment configuration sheet, rather than mindlessly adding compatibility to improve the compilation quality of the code.

In plain English, the target environment configuration table tells Babel what the target browser has, and if the target browser doesn’t support an API or syntax, Babel handles it automatically.

How do I modify and configure the target environment profile table? The answer is to look at the official website document BrowsersList, or, more simply, to see how it is configured in a project generated by Vue-CLI or Create-React app. Understand the meaning of the field and change it as you use it.

If the target environment configuration table BROWSERSLIST is not configured in the project, you can specify a default configuration

Profile type:

Babel has two parallel configuration file methods:

  • Project-wide configuration
  • File-related configuration (File-Relative)

    • .babelrc(and.babelrc.js) file
    • A package.json file with “Babel” key
Version Changes
v7.8.0 support.babelrc.mjs , babel.config.mjs
v7.7.0 support.babelrc..babelrc.json..babelrc.cjs.babel.config.json.babel.config.cjs

The difference between the two configuration files, if you do not understand it can be temporarily skipped, does not affect the future of learning, after the end of the final, in the back to carefully consider

Configuration of the project scope

A new feature in Babel 7.x. Babel has the concept of a “root” directory, which defaults to the current working directory. Compile time, Babel will automatically search relative to the root directory of the Babel. Config. Js file, or its Babel approved documents, such as: Babel. Config. Json, Babel. Config. CJS, Babel. Config. MJS, etc

advantages

These are very suitable and widely applicable configurations, and even allow plugins and presets to be easily applied to files in node_modules or symlinked packages

disadvantages

Because it depends on the working directory, if a project is of Monorepo type, the configuration file will not be found at compile time if the working directory is not root, which makes it painful to use in Monorepo.

babel.config.js
package.json
packages/
  mod1/
    package.json
    src/index.js
  mod2/
    package.json
    src/index.js

When each submodule is built, the user will need to manually set its path through rootMode to load the babel.config.js file

CLI
babel --root-mode upward src -d lib
Webpack
module: {
  rules: [
    {
      loader: "babel-loader",
      options: {
        rootMode: "upward",
      },
    },
  ];
}

See the official documentation for more details

File related configuration

At compile time, Babel searches for.babelrc.json or other Babel-approved configuration files, starting from the directory where the file being compiled is located. Such as: babelrc. Babelrc. Js, / package. Json# Babel. With this capability, you can create separate configurations for submodules of the Package. At the same time, both file – and project-related configurations can be used together. Here’s the official explanation:

File-relative configurations are also merged over top of project-wide config values, making them potentially useful for specific overrides, though that can also be accomplished through “overrides”.

Popular translation is the following two points:

  • Different configurations: File-related configurations and project-related configurations can be combined
  • Same configuration: File-related configuration overrides project-related configuration

    babel.config.js
    package.json
    packages/
    mod1/
      package.json
      src/index.js
      .babelrc
    mod2/
      package.json
      src/index.js
      .babelrc

<! —

  • @Desc:
  • @FilePath: /tutor-babel/docs/md/start.md
  • @Author: liujianwei1
  • @Date: 2021-05-14 16:43:54
  • @LastEditors: liujianwei1
  • @Reference Desc:

–>

In the real world, Babel requires engineering collaboration and interoperability with tools such as Webpack, because Babel must be large and complex. Let’s start by configuring the simplest Babel compilation project to get familiar with the process.

The source address

Demo code address: Tutor-Basic Portal

The installation

Create a Tutor-Basic project. Install the NPM package

npm install --save-dev @babel/core @babel/cli @babel/preset-env

Configuration and compilation

Step 1: Create a new.babelrc file (or babel.config.js,.babelrc.js) under the root directory. Add the following

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

Step 2: Add the following configuration in the scripts of package.json file

"scripts": {
    "build": "babel src/index.js --out-file dist/index.js"
  }

Step 3: Create a new lib/index.js file and add the following contents

let number1 = 10
let number2 = 20
const sum = (num1, num2) => num1 + num2

Step 4: Run the command

NPM run build # or yarn build # or NPX Babel SRC /index.js -- out-of-file dist/index.js

Step5: View the compiled results

"use strict";

var number1 = 10;
var number2 = 20;

var sum = function sum(num1, num2) {
  return num1 + num2;
};

The above shows one of the simplest Babel use projects, output results and
Babel is introducedThe result is the same

other

  • @babel/core: Babel implements the core of the transformation, which can be configured according to (.babelrc) rules, source code conversion, to provide the basic conversion ability
  • @babel/cli: Command-line functionality provided by Babel, dependency@babel/core, run from the command line in a terminal to compile a file or directory.
  • @babel/preset-envallowTo configureTo be supportedThe target environmentProvides ES6 to ES5 syntactic conversion rules. If you do not use it, you can do the conversion, but after the conversion you will still have E66, which means that there is no conversion.
  • Babelrc Babel configuration file. By default, when compiling, it looks for the configuration file under the current project root directory. The transformation rules are all written in here. More on that later