introduce
Babel is a toolchain designed to make ECMAScript 2015+ version code backward compatible with Javascript syntax so that it can run in older browsers or other environments.
JavaScript as a language is constantly evolving, with new standards/proposals and new features emerging all the time. Babel lets you use them years in advance, even before they become widely available.
The three main processing steps of Babel are parse, Transform, and generate.
- parsing
Parse code into an abstract syntax tree (AST). Each JS engine (such as Chrome’s V8) has its own AST parser, and Babel is implemented in Babylon. There are two stages in the parsing process: lexical analysis and syntax analysis. Lexical analysis converts string code into a stream of tokens, which are similar to nodes in an AST. The parsing phase converts a token flow into an AST, and the information in the token is converted into an AST representation.
- conversion
At this stage, Babel accepts the AST and traverses it through the Babel-traverse depth-first, adding, updating, and removing nodes along the way. This is where the Babel plug-in comes in.
- Generation converts the transformed AST into JS code via Babel-Generator by depth first traversing the entire AST and then building a string that can represent the converted code.
For example, Babel is able to add the new ES2015 arrow function syntax:
const square = n= > n * n;
Copy the code
Translated into:
const square = function square(n) {
return n * n;
}
Copy the code
Babel module introduction
1.babel-core
Babel’s core modules include some core apis such as Transform.
/* * @param {string} code Code string to be translated * @param {object} Options Optional configuration item * @return {object} */babel.transform(code: string, options? :Object)
// Return an object with three main parts:
{
generated code, / / generated code
sources map, / / the source map
AST // Abstract syntax tree
}
Copy the code
More about AST
Some packaging or build tools that use the Babel plugin use this method. Here is some source code imported into the Babel plugin:
//gulp-babel
const babel = require('babel-core');
/* some codes... * /
module.exports = function (opts) {
opts = opts || {};
return through.obj(function (file, enc, cb) {
try {
const fileOpts = Object.assign({}, opts, {
filename: file.path,
filenameRelative: file.relative,
sourceMap: Boolean(file.sourceMap),
sourceFileName: file.relative,
sourceMapTarget: file.relative
});
const res = babel.transform(file.contents.toString(), fileOpts);
if(res ! = =null) {
//some codes}}catch (err) {
//some codes}}}//babel-loader
var babel = require("babel-core");
/* some codes... * /
var transpile = function transpile(source, options) {
//some code
try {
result = babel.transform(source, options);
} catch (error) {
//some codes
}
//some codes
}
//rollup-pugin-babel
import { buildExternalHelpers, transform } from 'babel-core';
/* some codes... * /
export default function babel ( options ) {
//some codes
return {
// some methods
transform ( code, id ) {
const transformed = transform( code, localOpts );
//some codes
return {
code: transformed.code,
map: transformed.map }; }}}Copy the code
2.babel-cli
Babel’s CLI is an easy way to use Babel to compile files from the command line. Mainly used for file input and output.
Global installation
npm install -g babel-cli
Copy the code
We can compile our first file like this:
babel test.js
// The compiled file is output at the terminal
Copy the code
babel test.js -o test-out.js
// The compiled file is printed in the test-out.js file
Copy the code
Run the Babel CLI within the project
Although it is possible to install Babel CLI globally on your machine, it is better to install it locally on a project by project basis. There are two main reasons.
- 1. Different projects on the same machine may rely on different versions of Babel and allow you to select updates.
- 2. Means that there is no implicit dependency on the working environment, so that the project has good portability and easy installation
Install Babel CLI locally to run:
npm install --save-dev babel-cli
Copy the code
Instead of running Babel directly from the command line, we write the command in a package.json script.
Simply add the “scirpts” field to your package.json file.
{ "scripts":{ "build": "babel src -d lib", ... },... }Copy the code
It can now be run from the terminal:
npm run build
Copy the code
This will run Babel in the same way as before.
3.babel-node
Babel-node is installed with Babel-CLI. Once babel-CLI is installed, Babel-Node is delivered with babel-CLI. Entering babel-node on the command line starts a REPL (read-eval-print-loop), which is a JS execution environment that supports ES6.
4.babel-register
Babel-register is a registry for Babel that overwrites node’s require method. After babel-register is introduced, modules requiring.es6,.es,.jsx, and.js will be translated by Babel.
//test.js
const name = 'test';
module.exports = (a)= > {
const json = {name};
return json;
};
//main.js
require('babel-register');
var test = require('./test.js'); // The es6 syntax in test.js will be translated into ES5
console.log(test.toString()); // See if the console output has been translated by the toString method
/* function () { var json = { name: name }; return json; } * /
Copy the code
5.babel-polyfill
The main purpose of Babel-Polyfill in the code is to use existing syntax and apis to implement apis that browsers have not yet implemented, and to fix some of the flaws in the browser. For example, Array has new includes methods that I want to use, but don’t have them on earlier versions of the browser, and introducing Babel-Polyfill helps us add these methods.
Projects using
1. .babelrc
All Babel operations will read the configuration file, except for those that set options in the callback function. If the configuration file is not available, it will read the configuration from the Babel property of the package.json file.
2.plugins
Plug-ins in Babel tell Babel what we need to translate by configuring different plug-ins.
3.presets
Presets are a collection of plugins, just like retouching. Save some of the parameters from the last retouching as a preset and use it directly next time.
// cnpm install -D babel-preset -env
{
"presets": [["env", {
"targets": { // Specify which environment to translate to
// Browser environment
"browsers": ["last 2 versions"."safari >= 7"]./ / the node environment
"node": "6.10".//"current" uses the current version of node
},
// Whether to translate ES6's modularized syntax into other types
Umd / / parameters: "amd" | "" |" systemjs "|" commonjs | "false, the default for 'commonjs'
"modules": 'commonjs'.// Whether to perform the debug operation, the console will print the log of all plug-ins, the version of the plug-in
"debug": false.// Enable certain modules forcibly, default is []
"include": ["transform-es2015-arrow-functions"].// Disable certain modules, default is []
"exclude": ["transform-es2015-for-of"].// Whether to automatically introduce polyfill. To enable this option, you must ensure that babel-polyfill is installed
// Parameter: Boolean, default is false.
"useBuiltIns": false}}]]Copy the code
There are two things to note about the last argument, useBuiltIns:
- 1. If useBuiltIns is true, babel-polyfill must be introduced into the project.
- 2. Babel-polyfill can only be introduced once. Multiple introduction will cause global scope conflicts.