Babel
It’s official: Convert javascript code from ECMAScript 2015 or later to backward-compatible versions of javascript code in older browsers or environments.
In short, turn incompatible JavaScript code into compatible, executable JavaScript code.
Function:
The syntax conversion
Add some compatible polyfill functionality
Source code conversion etc.
Simple configuration preview:
{"plugins": [], // Plugins with "presets": [] // default configuration} // here is.babelrc configuration // the official website recommends using the module configuration, bable.config.js const presets = [] const plugins = [] module.exports = { presets, plugins }Copy the code
Configuration Introduction:
Presets: A set of plugins that contains all the functionality of a plugin.
Plugin: Converts code that needs to be converted into code that the browser can execute.
Order of execution of compilation:
1. Execute all plugins
2. Plugins are sequentially compiled by dependency
3. All plugins are completed before the presets are executed.
4. Presets are executed in reverse order. (Execute from last)
5. Complete the compilation.
1. Introduction of main plug-ins
Babel-preset – ES2015 (ES2015 / ES6 plugin set)
Convert ES2015(ES6) javascript code to browser-compatible javascript code
Arrow-functions: arrow functions
Block-scoped-functions: switch from naming functions to assigning values
Block-scoping: let to var
Classes: Es6 class transformations
Computed -properties: Transformation of attribute names, for example: var obj = {[‘x’+a]: 1}
Destructuring: Destructor conversion
Duplicate-keys: attribute optimization
For of: for of
Function-name: specifies the name of the optimized function
Instanceof: Transformation of instanceof
Literals: Optimization of different types of replication
New-target: inherits the extends transformation
Object-super: super conversion
Parameters: params, (a=1,b=2)=>{
Shorthand – properties: object attribute transformation {a, b} = > {} a: a, b, b
Spread: spread attribute conversion {… other}
Sticky -regex: Regex optimization, built with new Regex
Template-literals: string template
Typeof -symbol: Symbol conversion
Unicode-regex: Converts a regular match string to Unicode
Babel-preset – ES2016 (ES2016 / ES7 plugin set)
Convert ES2016(ES7) javascript code to browser-compatible code
Exponentiation-operator: exponentiation of x **= 3, the 3rd power of x
Babel-preset – ES2017 (ES2017 / ES8 plugin set)
Convert the ES2017(ES8) code
Async-to-generator: Converts async/await to a generator function
Babel-preset -stage-x (ES2018/ Stage plugin set)
Convert the code for the stages
Async-generator-function: converts asynchronous functions
Dotall – Regex: Dot regular optimization
Object-rest-spread: parsing optimization
Optional catch-binding: catch and finally optimization
unicode-proprty-regex
Modules
modules-amd / modules-commonjs / modules-systemjs / modules-umd
Convert different export Default X modules into different modules amd/CommonJS/SystemJS/UMD
Experiental
Class-properties: Static property conversion of a class
Decorators: Decorator conversion
do-expressions
Export-default-from: export optimization
Export-namespace-from: export optimization
Fun => fun.bind(obj) ::obj. Fun => obj. Fun (obj)
function-sent
logical-assignment-operators
nullish-coalescing-operaor
numeric-separator
optional-chaining
pipeline-opertor
throw-expressions
Minification (Babel – minify)
Optimize plug-in presets with code compression
.
Here you can go to the official website to check…
Babel-preset -react (React set)
React…
JSX and Element transformations
Just add the React default.
Other Other plug-ins
Jscript: Strict schema naming
Object-assgin: Assgin conversion
Regenerator: Conversion of generator functions
Object-set-prototype-to-assign: setPrototype conversion
runtime
2. Introduction of main presets
@babel/preset-dev
Is an intelligent preset.
Babel plug-ins and Polyfills are automatically determined based on the browser and runtime environment.
Same as babel-preset-latest (used with ES2015 / ES2016 / ES2017) if there is no configuration.
{
"presets": [ "dev" ]
}
Copy the code
Configuration and details:
{" presets ": [[' @ Babel/preset - env '{' target' : {" browser ": [" ie > = 8", "chrome > = 62"]. "Node", "8.9.0", "safari" : "tp"}, "modules" : false, "debug" : true, "Uglify ":true "useBuiltIns":true}]}Copy the code
Target: Describes the supported/targeted environment that you configured for the project
Browsers are supported. Browsers return a list of supported browsers. Will be overwritten by target.ie
[‘ie>=8’] An environment that supports IE8
“Default” by default
Node: Specifies the Node environment and can specify the version
Safari: Indicates the Safari version
Modules: Enables converting ES6 to other modules
Debug: Whether to enable console.log
Include/exclude: Specifies the plugin function that must be enabled or plugin function that is not enabled
Uglify: Compressed code
UseBuiltIns:
False: Reference all babel-polyfill entries and add babel-polyfill entry to webpack:
Entry :[‘babel-polyfill’, ‘index.js’], reference all polyfills, size becomes larger
True: reference part, reference polyfill, based on preset-env environment,
Reference babel-polyfill in the entry file
@babel/preset-react
This is all a bunch of React related collections
There is no need to introduce, you need to go to the official website to browse.
Stage-x
The default in the draft..
The plug-in collection does not exist in the preset-env collection, so reference…. is required
3. Compatible method with Babel-Polyfill
Babel preset-dev only converts new Javascript syntax, not new APIS.
For example, Generator/Set/Map
Babel conversion is implemented after the code, there are still incompatible code conversion.
Principle:
Babel-folyfill is a prototype that modifies global objects, adds incompatible API methods, or modifies incompatible API methods.
Usage:
1. At the top of the entry file add:
require('@babel-polyfill');
import '@babel-polyfill'Copy the code
2. Add in webpack
{entry: [' @ Babel - polyfill ', '. / app. Js']}Copy the code
Add it in the webPack configuration file.
3. Reference directly in HTML, before packing js files
Copy the code
Transform-runtime plugin
The code transformed from Babel is transformed again, as with Babel-Polyfill, to resolve incompatible global apis.
Unlike Babel-Polyfill, it does not add/modify global objects.
It is a special treatment for incompatible methods, that is, adding helper methods to make them compatible.
And transform-Runtime is referred to when compatible transformations are required.
Transform-runtime relies on babel-Runtime, and the auxiliary methods refer to babel-Runtime
Features:
Global variables are not tainted because global objects are not modified
There is no way to modify the instance, so some methods cannot be implemented.
["transform-runtime", {
"corejs":false, "helpers": false, "polyfill": false, "regenerator": true, "moduleName": "babel-runtime" }]Copy the code
Helpers: Whether to use @babel-Runtime /helpers instead of internal helpers
Coresjs: Whether to replace Map/Set etc methods with auxiliary methods in @babel-Runtime /corejs
Polyfill: Whether to use @babel-Runtime helper function instead of polyfill
Regenerator: Whether to replace async/generator with an auxiliary function
ModuleName: The name of the reference
5, @ Babel – register
Registering all current code with @babel-register requires transcoding
var fs = require('fs');
var babelConfig = JSON.parse(fs.readFileSync('./.babelrc'));
require('babel-register')(babelConfig);
Copy the code
Obviously, you can pass in a.babelrc configuration file to configure transcoding.
You just need to add it to the entry file.
Nodes can transcode Babel in this way.
6, the tools
Babel-parser: A parser for Babel that parses Javascript/JSX/Typescript/flow code
Babel-core: the core file of Babel, used for transcoding
Babel-generator: Code conversion, source code and conversion code
Babel-code-frame: transcoding mapping of code conversion positions
Babel-helpers: helpers
Babel-runtime: provides a list of helper methods, similar to polyfill
.
@bable/ Babel – CLI command line tool
It is used to compile files on the command line and perform configuration and output operations.
Usage:
Babel input.js -options // Compile the input.js fileCopy the code
Configuration:
-o: indicates the output path
-w: listens to compiled files in real time
-s: outputs source-map, which can be introverted
-d: When compiling a directory, -d prints the directory
–ignore: files to be ignored
— Plugins, plugins, plugins
— Presets: Use presets, use, and separate
–config-file: use the.babelrc file path
. Babelrc configuration details
Configuration transformation serves Babel in three different ways:
Configuration for syntax escape. Preset -env/stage-x is mainly used for syntactic escape of ES,
2. Configuration for patches, i.e. polyfill configuration. Primarily transform-Runtime.
React JSX/Flow, etc
Example:
{" presets ": [" react", [" env "{...}]," stage - 0] ", "plugins" : [" pluginName." [" transform - runtime, "{...}]]," ignore ": [" path", 'file'], "miniied" : Boolean, "comments" : Boolean, "Env" : {" test ": {" presets" : [], "plugins" : []}},... }Copy the code
Main configurations
Presets: Presets, a collection of plug-ins, executed in reverse order
Plugins: plugins are executed first, and then executed in preset order
Ignore: files that are ignored
Minify: Compressed code
Common: Whether comments are required
Env: sets different environments and applies different configurations. The configuration value is BABEL_ENV. If NODE_ENV is not set, the default value is development.
Others can be viewed on the official website…
The common default
Env: replaces the presets of ES2015 / ES2016 / ES2017. Introduce plug-ins based on the environment
React: A collection of react plugins
React -optimize: React code optimizations such as propsType removal to reduce production of the above code
Stage-x: a collection of draft code plug-ins
Flow: Collection of flow plug-ins
Minify: Collection of code optimizations
Typescript: A collection of typescript plug-ins
Common plug-in
Transform-async-to-generator: async/await plug-in for asynchronous functions
Transform-decorators-leagacy: decorator plug-in
Syntax-dynamic-import: import() plug-in
Transform-runtime: helper plugin for PloyFill
Transform-object-rest-spread: transform test = {a:1,b2}; var t = {… test,n:1}
Transform-funciton-bind: to compile obj::fun => fun.bind(obj)
Transform-es2015-modules-commonjs: the ES6 module is used in node
www.cnblogs.com/jiebba/p/96…
My blog: XiaoLong’s Blog
Blog garden subtotal baba: https://www.cnblogs.com/jiebba