What’s a Babel?
After studying ES6, the code is developed based on modularity; We started to use import and export for module import and export, but after module import and export, problems appeared:
- Es6 Internet Explorer does not support it
- Import is not supported by Google Chrome
When import is used,
The browser will report the following error: Uncaught SyntaxError: Cannot use import statement outside a module Failed to import imports from outside the module.
If you want your browser to support ES6, you need to find a way to compile your ES6 code into something that your browser supports. To get es6 code compiled for browser compatibility, you need to use the tool —– Babel
Babel
Liverpoolfc.tv: babeljs. IO /
Online compilation: babeljs. IO /repl
Use in node.js environment.
Babel is a Javascript compiler that converts es6 code into pre-ES6 code for the browser to recognize.
Here’s an example:
Here’s the ES6 code:
let name = 'Alex';
const age = 18;
const add = (x, y) = > x + y;
new Promise((resolve, reject) = > {
resolve('success');
}).then(value= > {
console.log(value);
});
Array.from([1.2]);
class Person {
constructor(name, age) {
Object.assign(this, { name, age }); }}new Person('Alex'.18);
import './index.js';
Copy the code
Js code compiled with Babel:
('use strict');
require('./index.js');
function _instanceof(left, right) {
if( right ! =null &&
typeof Symbol! = ='undefined' &&
right[Symbol.hasInstance]
) {
return!!!!! right[Symbol.hasInstance](left);
} else {
return left instanceofright; }}function _classCallCheck(instance, Constructor) {
if(! _instanceof(instance, Constructor)) {throw new TypeError('Cannot call a class as a function'); }}var name = 'Alex';
var age = 18;
var add = function add(x, y) {
return x + y;
};
new Promise(function (resolve, reject) {
resolve('success');
}).then(function (value) {
console.log(value);
});
Array.from([1.2]);
var Person = function Person(name, age) {
_classCallCheck(this, Person);
Object.assign(this, {
name: name,
age: age
});
};
new Person('Alex'.18);
Copy the code
Babel itself compiles most of ES6 syntax, such as lets, const, arrow functions, and classes
However, the new ES6 apis, such as global objects such as Set, Map, Promise, and some methods defined on global objects (such as object.assign/array. from), cannot be compiled directly, and need to use other modules
Babel generally needs to work with Webpack to compile module syntax
Preparations for using Babel
Using Babel is done in the context of Node
1. What are Node.js and NPM
Node.js is a platform or tool that corresponds to a browser
JavaScript = ECMAScript + IO + File +… Server operations
NPM: Node package management tool
NPM install Install….
2. Initialize the project
In the project directory, right-click to open the terminal
npm init
Generate the node_modules folder and package.json file in the directory
3. Install the packages required for Babel parsing code
npm install --save-dev @babel/core @babel/cli
The installation package
NPM install --save-dev @babel/[email protected] @babel/[email protected]
Installs the specified version of the package
4. Run
NPX Babel –version Displays the version number
npx
Local command tools:NPX command XXX
, omit NPX globally
Execute the compiled command
Add the command to execute Babel to the package.json file
babel src -d dist
babel src --out-dir dist
SRC is the name of the compiled file
Dist File name output after compilation
The -d parameter configures the output file name
–out-dir is the full name of -d
Run:
npm run build
Babel configuration file
.babelrc is created in a file
NPM install @ Babel/[email protected] – save – dev
Create the configuration file.babelrc and configure it
{
“presets”: [“@babel/preset-env”]
}
Use the @babel/preset-env plugin in this file to compile and transform the syntaxCopy the code
The compiled code is loaded into HTML for testing, and the compiled JS file is introduced into THE HTML file
Summary: The future encounter is js syntax compilation problem; Seek the Babel
Which tool in Babel is used to solve what problem
Tools in Babel in detail
Babel itself does not have any conversion capabilities, and without a plugin, the code that goes through Babel is the same as the input
1. Two Add-ons to Babel
Syntax plugin: Enables Babel to parse more syntax during parsing
Translation plug-in: Outputs code during transformation. Like translating the arrow function into a normal function
Where PRESET is a translation plug-in commonly used by Babel
@babel/cli
Terminal CLI tool.
@babel/preset-env
Preset is a set of specifications that contain dozens of translation plug-ins. This is a collection of plug-ins
@babel/core
The Babel compiler. Split into three modules: @babel/parser, @babel/traverse, and @Babel/Generator
@babel/plugin
Babel plug-in mechanism, easy extension, integration.
Other tools
Babel-loader: A Webpack loader that uses Babel to transform JavaScript dependencies. It is simply a Webpack and Babel intermediate layer that allows Webpack to parse js files with bable
@babel is a kind of official tag, a departure from the old days when people just picked names
Babel /preset-env: Babel-preset -env, depending on which browser you want to support, decides which translations/plugins and polyfills you should use, such as providing new features of modern browsers to older browsers.
@babel/preset-react: Babel-preset -react, the Babel preset for all react plugins, such as converting JSX to functions.
Babel-polyfill: By default, Babel only converts new JavaScript syntax, not new apis. For example, global objects such as Iterator, Generator, Set, Maps, Proxy, Reflect, Symbol, Promise, and some methods defined on global objects (such as object.assign) do not translate. If you want to use these new objects and methods, you must use Babel-Polyfill to provide a spacer for your current environment.
Babel-runtime is designed to solve the problem that the babel-translated code needs helper functions to do the same thing as the source code. These helper functions may be repeated in some modules, resulting in larger compiled code. So, a separate package, Babel-Runtime, is provided for compiling module reuse utility functions.
Libraries and toolkits generally don’t introduce polyfill directly until they use Babel-Runtime. Otherwise, global objects such as Promises contaminate the global namespace, which requires library users to provide their own polyfills. These polyfills are usually mentioned in the library and tool usage instructions; for example, many libraries will require es5 polyfills.
After using Babel-Runtime, libraries and tools simply add a dependency on Babel-Runtime in package.json and leave it to Babel-Runtime to introduce polyfill
Babel some inserts and usage
Please check the website before using it
babel-plugin-dynamic-import-node // Support import('comXXX').then()
babel-plugin-dynamic-import-webpack // Support import('comXXX').then()
babel-plugin-import // Supports on-demand loading of antD, ANTD-Mobile, Lodash, And Material - UI libraries
babel-plugin-syntax-dynamic-import // Support import('comXXX').then()
babel-plugin-transform-class-properties// Support to write properties and static properties directly within the classbabel-plugin-transform-decorators-legacy// Support decoratorsbabel-plugin-transform-runtime/ / convertES5Helper functions are needed, and all helper functions are grouped into one module to avoid alljsDuplicate helper function life in fileCopy the code
Babel presets and plugins
Babel plug-ins are generally broken down into as small a force as possible, and developers can introduce them on demand. For example, for the ES6 to ES5 function, Babel officially split into 20+ plugins.
The benefits are obvious, both in terms of performance and scalability. For example, if a developer wants to experience the arrow function feature of ES6, he can simply introduce the transform-ES2015-arrow-functions plugin instead of loading the ES6 bucket.
Many times, however, plug-in by plug-in is inefficient. For example, in a project where a developer wants to convert all the code from ES6 to ES5, the way plug-ins are introduced one by one is maddeningly laborious and error-prone.
At this time, Babel Preset can be used.
You can simply think of Babel Preset as a set of Babel Plugins. For example, Babel-Preset – ES2015 contains all the plugins related to THE ES6 conversion.