Writing in the front
In fact, I wrote a step-by-step tutorial on Babel before, but I didn’t feel good about that one and haven’t written it for a long time. Besides, I am preparing my blog recently, so I decided to write it again.
Babel Basics
Babel is introduced
Babel is a JavaScript compiler, a compiler, not a packer. It can help users convert some advanced features of the current ES to run in environments that are not currently supported. It is also possible to patch certain features for certain environments (syntax conversion, but some things are not supported by browsers), such as Internet Explorer. Of course, it can also convert some support such as JSX syntax conversions and type-checking flow syntax.
The installationbabel
mkdir babel_demo
cd babel_demo
npm init -y
npm i @babel/core @babel/cli -D
Copy the code
Prepare some regular ES6 code
src/index.js
let a = msg= > msg + `hello`
console.log(a(123));
Copy the code
Simple utility Babel/CLI command to compile code
npx babel src -d lib
Copy the code
You will find that the converted code has an exact copy, which is certainly not desirable
Babel configuration
So far, Babel hasn’t done anything for us, so let’s write a configuration that tells Babel how to compile the code. Babel configuration files can be JSON, JS, or.babelrc. There are many different ways to support babelrc, but here is the simplest and most common. A normal configuration file would look like this:
{
"presets": [],
"plugins": []
}
Copy the code
You can see from the configuration file that we need some presets as well as some plug-ins. So what are presets and what are plug-ins?
The plug-in
Plug-ins are at the heart of Babel, and everything Babel does is done by plug-ins. Plugins are usually responsible for the compilation of our es standard advanced feature code, such as plugins for arrow functions, plugins for class syntax, and plugins for frameworks like React, modularity, and type checking (flow or TS).
The preset
So what is a preset? Presets can be thought of as a set of plug-ins or configuration items. Just like your mobile phone plan, if you do not have a plan, you may need to open a separate phone, SMS, caller ID, data and other services, then you can also order a plan to save a lot of unnecessary trouble.
Plug-in experience
In order to verify the plug-ins, we take an arrow function plug-in to experience. The reason why we can’t talk about the syntactic plug-ins one by one is that there are so many new features of Es, and there are probably too many plug-ins to mention all of them, and they are not useful for general project development. For the specific list of plug-ins, you can refer to the list of plug-ins. Write an arrow function that contains only this syntax:
var fn = msg= > msg + '!!!!!! '
var str = fn('hello')
console.log(str);
Copy the code
Then install a plugin @babel/plugin-transform-arrow-functions to help us compile
npm install --save-dev @babel/plugin-transform-arrow-functions
Copy the code
Then add the plugin configuration under the root directory. Babelrc:
{
"plugins": [
"@babel/plugin-transform-arrow-functions"]."presets": []}Copy the code
Note that if you want to write extra configuration in the plugin, you need to write it like this
{
"plugins": [["@babel/plugin-transform-arrow-functions", { "spec": true}}]]Copy the code
When you compile again, you’ll be surprised to see that the arrow function code has been converted. I changed let to var to demonstrate the clipping function. What if I wanted to write let or const? Then we have to install another plugin @babel/plugin-transform-block-scoping. Oh, my God, this is so much trouble! All right, let’s go get a package from customer service.
Use the default
The most famous preset packages are @babel/preset-env(which contains a set of syntax-feature plug-ins) and @babel/preset- React, where the arrow function configuration plugin is removed. Install our presets
npm i @babel/preset-env -D
Copy the code
And then change the configuration
{
"plugins": []."presets": [
"@babel/preset-env"]}Copy the code
Compile again at this point, and you’ll see that the code still works. In general, sometimes we use browserList to specify what we want to build. For details on how to use this tool, look at Browserslist, which is used not only by Babel, but also by postCSS.
Polyfill gasket
What is the gasket, the above said Babel in addition to compile the code, can help us to patch, such as Es6 launched a new Array. The prototype. FindIndex this method, we can see from MDN ie browser does not support, that is to say, although you can write the grammar, But special circumstances it does not support, that how to do, do you need to judge is IE does not use this method or write a substitute up? Obviously not, when you think about all the new apis, each browser will probably have different support and will have to write when to write. There are actually people in the community who have done this already, notably code-js and the ReGenerator Runtime (mainly to patch promise). In the early days, Babel had a plugin called @babel/ Polyfill that contained the above two patch libraries, but the older version is now deprecated, but it is still available. This shim helps us extend the corresponding API on the global scope prototype.
Note the use of –save to install dependencies, as the library needs to be executed before running our business generation
npm install --save @babel/polyfill
Copy the code
Use @babel/polyfill, which can be used in several ways
1. In an environment such as Node \webpack\rollup, you may need to import it at the top of the entry file
require("@babel/polyfill");
Copy the code
or
import "@babel/polyfill";
Copy the code
2. In WebPack, you can also add:
module.exports = {
entry: ["@babel/polyfill"."./app/js"]};Copy the code
3, Use this with @babel/preset-env so you don’t have to introduce the shim library in the entry file.
{
"plugins": []."presets": [["@babel/preset-env",
{
"useBuiltIns":"usage"."modules": false}}]]Copy the code
Modules is set to false because this configuration item is a decoration, and you never know who uses it. There is also a corejs version configuration item in preset-env that may prompt you to install it during compilation, just follow this
4, in the browser environment through script, not recommended
The basic usage part is actually pretty clear by now, but if you look carefully you may have noticed that one problem with using gaskets is that they pollute the whole world.
@babel/plugin-transform-runtime
To solve the problem of global contamination, Babel provides the @babel/ plugin-transform-Runtime plugin. The installation
npm install --save-dev @babel/plugin-transform-runtime
Copy the code
npm install --save @babel/runtime
Copy the code
What are these two fairy bands doing? These two are actually helping us implement a common patch, but not adding global variables. The configuration files are as follows:
{
"plugins": [["@babel/plugin-transform-runtime", {"corejs":3}]],"presets": [["@babel/preset-env",
{
"useBuiltIns":"usage"."modules": false."corejs":3}}]]Copy the code
My code: SRC /index.js
let arr = [1.2.3]
console.log(arr.findIndex);
console.log(Object.assign);
Copy the code
The code converted before using Runtime is:
import "core-js/modules/es.array.find-index.js";
import "core-js/modules/es.object.assign.js";
var arr = [1.2.3];
console.log(arr.findIndex);
console.log(Object.assign);
Copy the code
It’s pretty clear we’ve contaminated the whole place. If our code were to be used by a third party, it would probably pollute someone else’s environment.
When runtime is used, the converted code is:
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import _Object$assign from "@babel/runtime-corejs3/core-js-stable/object/assign";
var arr = [1.2.3];
console.log(_findIndexInstanceProperty(arr));
console.log(_Object$assign);
Copy the code
You can see that the prototypical or static methods used directly have been replaced with methods starting with _.
So much for the basics of Babel. In fact, some of the confusing questions about everyday use of Babel are solved here. Most companies’ business does not involve writing the underlying source code or plug-ins, and there will be time to fill in the next chapter later.