What is the Babel

1.Babel is actually a JavaScript'compiler'.2.In the new'api'Layers we can use'corejs'In fact, in the case of front-end engineering today, you need to be compatible with the runtime environment. In addition to the corejs shim API, there are a few things to consider2.1Syntactic conversions are generally a degradation of high-level language features'Grammatical level'
   2.2. Implementation and access of Polyfill feature --'the API level'
   2.3. Source conversion, such as JSX, etc. Possible with the development of the future development of the front-end appears more and more possible, if blindly to certain tools must have all function directly Inevitably there will be a bloated code3.From the perspective of engineering, we need to design a tool chain adhering to the following concepts to solve the above problems3.1Pluggable, for example, Babel needs a flexible plugin mechanism to bring third-party developers together and easy access to tools.3.2.debuggable, such as Babel, provides a set of sources during compilationMap, to help users build a mapping relationship between the compiled results and pre-compiled source code, convenient debugging;3.3. Compact based, flexible configuration, developers in'Restore specifications as far as possible'and'Smaller compilation output volume'Find a balance between.4.Think of an idea to use'Babel'The function of the JS compiler can convert code into ast syntax tree, which can be converted with various pluggable components to intervene in it, and with the future update of new scenarios, only plug-ins will be needed to match'babel'Parsing is as possible as you wantCopy the code

Installation procedure

1.In the use of'babel'When we generally need to install'@babel/core' '@babel/cli' '@babel/preset-env'
2.Since babel7, all official plug-ins and major modules have been placed under the @babel namespace. This avoids the problem of the names associated with Babel being hijacked in the NPM repository.Copy the code

The configuration file

1.Babel is also configurable and has similar configurations to other tools: ESLint (`.eslintrc`), Prettier,`.prettierrc`).'babel'Priority of the configuration file'babel.config.json < .babelrc < programmatic options from @babel/cli'

2.Babel is a JavaScript compiler. But out of the box Babel does nothing. It simply copies the source files to the build directory. We just analyzed that we need some coordination'Pluggable tool', so you can specify this type of default plugin here and simply say you don't configure either of these two'babel'I don't know what rule you're converting to."presets": []./ / the default
  "plugins": []   / / the plugin
}

3.The Babel of'Preset'You can think of it as a Babel'plugins'Plug-ins, for example'@babel/plugin-transform-arrow-functions'The function is to convert the arrow function of ES2015 into a common function of a plug-in, but es6 after the syntax conversion is a lot, this corresponding number of plug-in configuration is undoubtedly huge more plug-in more plug-in reference address'https://babeljs.io/docs/en/plugins'The corresponding'babel'provides'babel-preset-env'Integrate the latest syntax set into more presets'https://babeljs.io/docs/en/presets'
Copy the code
The same article you can refer to as me

Babel6-loose-mode. ht you can also check this out

babel api

1.Now that you know Babel is a compiler, you need a variety of plug-ins to translate the syntax1.1Parsing: Parsing code strings into abstract syntax trees.1.2Transformation: Transforms the abstract syntax tree.1.3. Code Generation: generates Code strings according to the transformed abstract syntax tree. Parse the source code string to make the computer understand the code, generate an AST, convert the changes to the AST into additions, deletions, and then print the AST as the object code string'Source code -> AST -> Converted AST -> converted code'
Copy the code

What is @babel/core

1.That was analyzed just now'babel'It's the syntax that helps us with the conversion'Abstract Syntax Tree (AST)'And Babel is no exception:2.The whole complicated process is'@babel/core'And of course this package depends on these packages'@babel/parser, @babel/traverse, @babel/generator'
3.'@babel/core'The main function is compilationCopy the code
I’m going to use @babel/core
1.Now what I want to do is use'@babel/core'Take this code'const a = 1'Become es5'var a = 1'
Copy the code
  • Case a
1.Don't use'presets''plugins'Found using'@babel/core'Didn't get the results you wanted to prove a word'Babel is a JavaScript compiler. But out of the box Babel does nothing. It just copies the source files to the build directory.
Copy the code
const core = require('@babel/core')

const code = 'const a = 1; '
core.transform(code, {}, (err, result) = > {
    console.log(result, err) // => { code, map, ast }
    // result
})
Const a = 1; const a = 1; const a = 1
Copy the code
  • Case 2
1.Using presets'@babel/preset-env'At this point packing gets the desired result'const a =1'Turned out to be'var a = 1'
Copy the code
const core = require('@babel/core')
const env = require('@babel/preset-env')

const code = 'const a = 1; '
core.transform(code, { presets: [env] }, (err, result) = > {
    console.log(result, err) // => { code, map, ast }
    // result
})
// print the result code field and get the result '"use strict"; \n\nvar a = 1; 'Got what I wanted
// Verify again that 'Babel is a JavaScript compiler. But out of the box Babel does nothing. It just copies the source files to the build directory.
// We need to configure the rules that tell him to convert
Copy the code
  • Case 3
1.The whole'@babel/core'The ability from the lower level'@babel/parser','@babel/code-frame','@babel/generator','@babel/traverse','@babel/types', which can be seen in the screenshot below2.In view of the beforeParsing.,'Transformation','Code Generation'The trilogy in turn corresponds to the package above2.1.Parsing.@babel/ Parser converts source code to AST2.2.'Transformation'.'@babel/traverse', you can traverse the AST and call the Visitor function to modify the AST,'@babel/types'Packages provide the ability to modify specific AST nodes (AST judgment, creation, modification, etc.)2.3. '@babel/generator'The new AST is aggregated and JavaScript code is generated, along with sourcemap for the other packages' @babel/code-frame', encountered an error halfway to print the code locationCopy the code
  • Source code core-js/lib/index.js part of the source code screenshot

const parser = require('@babel/parser')
const t = require('@babel/types')
const generate = require('@babel/generator').default
const traverse = require('@babel/traverse').default

const code = 'const a = 1; '

// Convert source code to AST
const ast = parser.parse(code)
traverse(ast, {
    VariableDeclaration(node, parent) {
        // console.log(node, parent)
        console.log(node.container[0].kind)
        node.container[0].kind = 'var'
        // const { node } = path
        // // // Obtain the function name
        // // path.replacewith () // replaceWith a new node
        // // path.remove() // Delete the current node
        // // path.skip() // Skip child nodes
        // const newNode = t.variableDeclaration('const', [t.variableDeclarator('var')])
        // path.replaceWith(newNode)
        // const copyNode = t.clonode (node) // Copies the current node
        // traverse(copyNode, {}, {}, path) // traverse(copyNode, {}, {}, path) // Traverses and replaces subtrees without affecting the current path}})const output = generate(ast)
console.log(output)
// Instead of relying on '@babel/core', we take the whole core package apart and execute it step by step to get the result we want
// { code: 'var a = 1; ', map: null, rawMappings: undefined }
Copy the code
API content specific explanation

Babel API ‘@babel/parser’, ‘@babel/code-frame’,

‘@babel/generator’, ‘@babel/traverse’, ‘@babel/types’ in detail

The whole process

Source of content, I suggest you read the whole article before looking at this

Syntax tree parsing tool

Ast syntax tree

You can refer to the section on AST transformations

How to write a custom Babel code conversion must read

You can refer to the article section on handwriting plugins

Write a quick plugin for Babel 2

You can refer to the article – on how to use

Babel /traverse usage notes

@babel/preset-env

1.'babel/preset-env'Babel6 is a collection of plugins that include es2015, ES2016, es2017, the latest syntax conversion plugins that we use in Babel6, allowing us to use the latest JS syntax, such aslet.const, arrow functions, and so on, but not below Stage3JavaScript syntax proposal. So we just need to install one later'babel/preset-env'That solves most of the problem. In short, it is'Babel a preset'It is mainly used to help us convert the grammar, and will automatically convert the JS grammar according to the current environment.Copy the code
Combining configuration files
1.Now comes the question that I'm phasing out with the earlier version of the browser, and some of the syntax of the new features is already supported in the new browser, is it necessary to convert all of them into'es5'We would prefer it to automatically load the plugins required by the current browser based on your configured browser list, and then convert the ES syntax2.You can specify the syntax of the lowest version browser compatibility through the configuration file'Browserslist'Browserslist data comes from'https://caniuse.com/'Now we know that the syntax supported by each browser version is followed by config files. Config files are used with the following priorities:2.1. @ Babel/preset - the targets in the env2.2Json browserslist field. Package. json2.3.browserslistrc configuration fileCopy the code
Simple case Study
1.Preparation Installation'@babel/core' '@babel/cli' '@babel/preset-env'├─ lib │ ├─ ├─ ├─ ├─ index.config. json ├─ lib │ ├─ ├─ ├─ ├.txt// It can also be a.babelrc file├─ ├─ package-lock, ├─ package-lock, ├─ package-lock2.Instructions for subsequent execution'npx babel src/index.js --out-dir lib'
3.If the following'babel.config.json'The contents of the file are just {"presets": [["@babel/env"[]} we run the command in step 2 to find index.js in lib:   "use strict";
    var a = 1;
    console.log(a);
    var p = new Promise(function (res) {
      console.log(res);
    });
    p.then(function (res) {
      console.log(res);
    });
'const'The way we want it to be'var'.'Promise'Because it is API and not syntax, there is no translation as we would expect4.You will now'babel.config.json'Change it to the following form, but pay attention to what we've written at this point'targets'For the"chrome": "70"Since our project no longer wants to execute this annoying IE, run the command and type the following in index.js in the lib folder    "use strict";
    const a = 1;
    console.log(a);
    const p = new Promise(res= > {
      console.log(res);
    });
    p.then(res= > {
      console.log(res); }); Because Google Chrome70The version is perfectly supportedconstSo Babel doesn't have to'const'Converted to'var'
5.Here are more recommended configurations'.browserslistrc'Because not only JS can choose this form depending on the configuration, follow up if you know'postcss-loader'It turns out that this is similar, we don't put these control files in their specific configuration file, but put them in a global file and this similarity can identify files uniformly'.browserslistrc'In this way, it can be managed globallyCopy the code
@ Babel/preset – corejs env
1.'@babel/preset-env'Is the'Syntactic conversion'.'corejs'Is the API conversion, the two actually need to be combined with each other to perfectly make ES browser compatible2.'@babel/preset-env'Provided a'useBuiltIns'The parameter can be set to three values'entry'.'usage'.'false'
  2.1."useBuiltIns: false"Not at this time'API gasket does the operation'You can bring in whatever processing you want'es api'The gasket such as this needs to be introduced in the file'import "core-js/stable"''import "regenerator-runtime/runtime"', ignore configured browser compatibility and introduce all polyfills.2.2."useBuiltIns: entry"Introduce browser-incompatible polyfill based on configured browser compatibility. Need to import files in the entry file hand file'import "core-js/stable"''import "regenerator-runtime/runtime"', will automatically replace all polyfills that are browser incompatible according to Browserslist. Here you need to specify the version of core-js (that is, to set'corejs'Field version)2.3."useBuiltIns: usage"Polyfill based on the browser compatibility configured and the API used in your code to add on demand. Summary Recommended use."useBuiltIns: usage"Configuration his own motion will do to help us introduce'corejs shim', does not need to be manually imported globally, and will match the specified browser version3.@babel/preset-env + useBuiltins (entry) + preset-env targets @babel/preset-env defines the required plugin preset for Babel, Meanwhile, polyfills are automatically loaded as needed by Babel based on preset-env targets support environment. When useBuiltins is set to Usage, it can be true based on the code, Parsing AST (Abstract syntax tree) for more fine-grained on-demand citation annotations:'regenerator'Facebook made it happen'aync''runtime'Library, used by Babel'regenerator-runtime'To support implementation'async' 'await'Support.Copy the code
  • Small examples of configuration
  {
      "presets": [["@babel/preset-env",
          {
            "modules": false."useBuiltIns": "entry".targets: { chrome: 44 }
            "corejs": 3,}]],"plugins": []}Copy the code

core-js3

  • UseBuiltIns: false

How does “useBuiltIns” implement the core-JS API
1.Why are you configuring"useBuiltIns"It can help us to introduce core-JS API suitable for the corresponding environment, the main reason'@babel/preset-env'Close using the targets parameter, according to the Browserslist specification'core-js-compat'To select polyfills (or plugins) that fit the environment, and to fill gaskets as needed through proper configurationCopy the code
We can refer to the configuration file for detailed configuration

(@babel/preset-env)

This part of the knowledge source

1. Babel 7 Upgrade Practice

What is @babel/polyfill


1.The @babel/ Polyfill module includes core-JS and a custom ReGenerator Runtime module along with it'core-js@3'Update,'@babel/polyfill'from'core-js@2'The transition to'core-js@3'What, in'@babel/polyfill'Has been abandoned,2.Import on usage"import 'babel-polyfill' "But at Babel7.4After version @babel/ Polyfill has been deprecated, core-JS and Regenerator-Runtime modules need to be installed separately3.This is no longer used, even if you want to use it in the configuration Babel file'"corejs": 2, 'This setting is fine, and the only differences are the differences specified for their corejs versionsCopy the code
More Configuration Items

Of course, the actual configuration value is much larger than ‘modules’,’useBuiltIns’,’corejs’ configuration items, see the official website for more information

@babel/runtime

1.Just mentioned'babel'Cooperate with'@babel/preste-env'Syntax conversion can be performed toclassConverted to an example diagram, provides onehelpersFunctions that provide help with conversion are all in '@babel/runtime'2. That is @babel/runtimecontainsBabelSome runtimes required for compilationhelpersFunction for business code to introduce modularityBabel helpersFunction, and it providesregenerator-runtimeforgeneratorasyncFunction to perform compilation degradation.Copy the code
  • The class conversion

@babel/plugin-transform-runtime

1.In the use of'core-js'Core-js, as I said, has five spin-off packages, of which'core-js-pure'(a version of core-js that doesn't pollute global variables) inject polyfills if we want to use this version'core-js'Use with Babel'@babel/plugin-transform-runtime 'This plugin of course this package is for more than that1.1.babel/plugin-transform-runtime solves global pollution problems because it is used'core-js-pure'
 1.2. After removing the syntax conversion inline of auxiliary function (the inline Babel helpers), using the @ Babel/the number of auxiliary functions in the runtime/helpers to replace. This saves us the hassle of manual introduction.Copy the code
Babel /plugin-transform-runtime resolves global code contamination problems
  • If you don’t use ‘@babel/plugin-transform-runtime ‘
1.The following code is not used'@babel/plugin-transform-runtime 'You can see that even though you're converting the API, you're actually causing global contamination and you can see that after converting you're importing onePromise
Copy the code

  • Use the ‘@babel/plugin-transform-runtime ‘configuration as follows
{
    "presets": [["@babel/env",
        {
            "corejs": 3."useBuiltIns": "usage"}]],"plugins": [["@babel/plugin-transform-runtime",
          {
            "absoluteRuntime": false."corejs": 3."helpers": true."regenerator": true."useESModules": false,}]]}Copy the code

Babel /plugin-transform-runtime resolves helper code
  • Using the ‘Babel/plugin – transform – runtime’
1.Introduce the helpers function uniformlyCopy the code

  • Babel /plugin-transform-runtime not used
1.If each of them hasclassAll files automatically introduce this and that will add an extra definitionCopy the code

What should I do to summarize the new Babel

1.You need Babel to work with the plug-in to help you with the syntax translation and that's what you're choosing'@babel/env' 
2.right'api'Conversion requires coordination'core-js''regenerator-runtime/runtime'But make use of'@babel/preset-env 'Provided in the'useBuiltins'You don't have to manually import in a global file'core-js''regenerator-runtime/runtime'
3.in'Syntactic conversion'when'@babel/runtime'Some will be provided to help with the conversion'helper'Function, but need to be used when you want to further optimize'@babel/plugin-transform-runtime', can help solve'Core-JS Global Contamination Problem'and'Move to remove inline helper function after syntactic conversion'
Copy the code
reference

Babel /plugin-transform-runtime read the description of babel-plugin-transform-runtime

polyfill-service

1.It can determine which features are missing in the current browser according to the UA of the browser, and then complement them. The problem is that some browsers modify the UA, so there are problems in some cases2.This solution'https://polyfill.io/v3/', through the introduction of CDNCopy the code

Online packaging

Polyfill. IO/v3 / url – buil…

Online transfer tool

Online transfer tool

About browser Version

The browser version is about the.babelrc file

Some references to the article

About abstract syntax trees and what Babel is, What do you need to know about Babel? What do you need to know about Babel