The principle of the author

Processing flow

Babel is a compiler

  • Parsing: Parsing the original code into an abstract syntax tree AST
    • Lexical analysis: The original code is broken up into tokens
    • Syntax analysis: Iterate through the Tokens array recursively to construct the AST
  • Transform: Transform the AST to generate a new AST
  • Generation: Iterate over the new AST to generate object code

reference

  • Babel
  • A brief analysis of how Babel works

The core concept

The plug-in

The initial Babel case does not do any conversion to the code

With Babel-traverse, the plugin can traverse the AST and make additions, deletions, and changes to the code

The default preset

The plug-in itself may have a separate plug-in for each syntax to do the conversion

Babel abstracts Preset to manage a set of plug-ins

Core packages

@babel-core

Include:

  • @babel/parser: is responsible for parsing source code into AST
  • @babel/traverse: Provides the capability to traverse AST nodes
  • @babel/generator: Is responsible for generating object code based on the transformed AST

@babel/cli

Provides the ability to call @babel/core from the command line

NPM I --save-dev @babel/core @babel/cli // No plugins are configured, the code before and after compiling is exactly the same NPX Babel SRC --out-dir distCopy the code

@babel/preset

// Preset depends on installing NPM I -- save-dev@babel /presetCopy the code
// .babelrc
{
  "presets": ["@babel/preset-env"]}Copy the code

@babel/polyfill

As of V7.4.0, @babel/ Polyfill has been deprecated and core-JS and Regenerator-Runtime modules installed separately

  • core-jsA core implementation of Polyfill is provided
  • regenerator-runtimeAre run-time dependencies for generator and async/await

Core-js is a set of modular JS standard library

// .babelrc
{
  "presets": [["@babel/preset-env", {
      "useBuiltIns": "usage"."corejs": 3}}]]Copy the code

@babel/runtime & @babel/plugin-transform-runtime

Babel inserts helper functions at the top of the module as it transforms code

class A {}
Copy the code

After the compilation

'use strict';

function _classCallCheck(instance, Constructor) {
  if(! (instanceinstanceof Constructor)) {
    throw new TypeError('Cannot call a class as a function'); }}var A = function A() {
  _classCallCheck(this, A);
};
Copy the code
npm install --save-dev @babel/plugin-transform-runtime
npm install --save @babel/runtime
Copy the code

_classCallCheck2 has been imported from @babel/ Runtime

@babel/plugin-transform-runtime changes all use of help methods from maintaining a separate copy to importing it from @babel/runtime

reference

  • The anatomy of the Babel