Instructions for using babel

What is babel?

babel is a JavaScript compiler. (The specific details can be viewed through the bable official website)

What is the role of babel?

The role of babel is to parse the high-level JavaScript grammar that the browser does not recognize into low-level grammar to achieve browser compatibility

Webpack can also parse advanced js syntax. Why do we need babel?

In webpack, only part of the new grammar of es6 can be processed by default. Some more advanced es6 grammar or es7 grammar cannot be processed by webpack; at this time, a third-party loader is needed to help webpack process these advanced grammars. When a third-party loader After the high-level grammar is converted to the low-level grammar, the result will be handed over to webpack and packaged into bundle.js.

Steps to use babel

Babel can help us convert high-level syntax to low-level syntax.
Step 1. In webpack, you can run the following two sets of commands to install two sets of packages to install babel-related loader functions.
The first package: cnpm i babel-core babel-loader babel-plugin-transform-runtime -D The
second package: cnpm i babel-preset-env babel-preset-stage-0 -D
Step two, open the webpack configuration file, In the rules array under the module node, add a new matching rule: {test:/.js$/,use:'babel-loader',exclude:/node_modules/}, when configuring babel's loader rules, you must Exclude the node_modules directory through the exclude option;
Insert picture description here
there are two reasons: 1. If node_modules is not excluded, babel will package and compile all the third-party js files in node_modules, which will consume cpu very much, and the packaging speed is very slow; 2. Even if babel has converted all the js in node_modules, the project cannot run normally.
Step 3: In the root directory of the project, create a new babel configuration file called .babelrc. This configuration file is in JSON format, so when writing .babelrc configuration, it must conform to the JSON syntax specification; comments cannot be written, and strings must be used Double quotes; then write the following configuration in .babelrc: You can translate preset into the meaning of [syntax]
{ "presets":["env","stage-0"], the grammatical name in the brackets is two sets of packages Suffixes in the grammar

"Plugins":["transform-runtime"] The name of the plug-in in brackets is the suffix in the two sets of plug-ins
}
Insert picture description here

Guess you like

Origin blog.csdn.net/dzhi1931/article/details/96912054