babel Basic Use Detailed Explanation

  • 2021-07-22 08:28:41
  • OfStack

What is babel?

babel is a powerful multi-purpose js compiler click to enter official website

Installing babel


npm install -g babel-cli 
npm install --save-dev babel-cli

babel Configuration File

Represented by. babelrc


{
 "presets" : [ ],
 "plugins" : [ ]
}

presets is used to store 1 preset

plugins is used to store 1 plug-ins

Simple use of the command line

We can compile a file with the-o (--out-file) parameter

babel es6.js -o es5.js / babel es6 --out-file es5.js

If we want to compile the entire catalog-d (--out-dir) parameter

babel  src -d build / babel  src --out-dir build

Preset

Now there is a section of es6 code, we want to use babel to compile this section of code, currently through the compiled code is almost intact copy over

es6.js


var add = (a,b) =>{
 console.log(a+b)
}
add(1,2)

We can install babel-preset-es2015 to parse the syntax of es2015

npm install --save-dev babel-preset-es2015

Then configure the. babelrc file


{
 "presets": ["es2015"]
}

In this way, we can parse the syntax of es 2015. Finally, by configuring scripts of package. json


"scripts": {
 "build" : "babel src -d build -w"
 }

Next, directly at the command line

npm run build

Plug-ins

There are many, many plug-ins in babel. For example, we want to convert the following 1 code into umd. What should we do?


var add = (a,b) =>{
 console.log(a+b)
}
add(1,2)

First find the corresponding plug-in babel-plugin-transform-es2015-modules-umd and install it

npm install --save-dev babel-plugin-transform-es2015-modules-umd

Introducing in the configuration


{
 "presets":["es2015"],
 "plugins":["transform-es2015-modules-umd"]
}

Then compile it and it's what we want


(function (global, factory) {
 if (typeof define === "function" && define.amd) {
 define(["module", "exports"], factory);
 } else if (typeof exports !== "undefined") {
 factory(module, exports);
 } else {
 var mod = {
  exports: {}
 };
 factory(mod, mod.exports);
 global.sum = mod.exports;
 }
})(this, function (module, exports) {
 "use strict";
 Object.defineProperty(exports, "__esModule", {
 value: true
 });
 var sum = function sum(a, b) {
 return a + b;
 };
 exports.default = sum;
 module.exports = exports["default"];
});

Integrated gulp

babel can be used alone or in combination with build tools (gulp, webpack, etc.)

First, download the babel plug-in corresponding to gulp and gulp

npm install gulp gulp-babel --save-dev

Create gulp configuration gulpfile. js


const gulp = require('gulp')
const babel = require('gulp-babel')
gulp.task('babel', ()=>{
 return gulp.src('src/**/*.js')
  .pipe(babel())  
  .pipe(gulp.dest('dist'))
})
gulp.task('default' , ['babel'])

scripts in package. json under configuration


"scripts": {
 "dev" : "./node_modules/.bin/gulp"
 }

Execute the command last

npm run dev


Related articles: