📅  最后修改于: 2020-10-27 03:19:52             🧑  作者: Mango
BabelJS是一个javascript编译器,可根据可用的预设和插件来更改给定代码的语法。 babel编译流程涉及以下3部分-
只需更改语法,就可以照原样返回给babel的代码。我们已经看到将预置添加到.babelrc文件中,以将代码从es6编译到es5,反之亦然。预设不过是一组插件。如果在编译过程中未提供预设或插件详细信息,Babel将不会更改任何内容。
现在让我们讨论以下插件-
现在,我们将创建一个项目设置并使用几个插件,这将使您对babel中的插件要求有清晰的了解。
npm init
我们必须为babel安装所需的软件包-babel cli,babel core,babel-preset等。
npm install babel-cli babel-core babel-preset-es2015 --save-dev
npm install @babel/cli @babel/core @babel/preset-env --save-dev
在您的项目中创建一个js文件,然后编写您的js代码。
请遵守以下为此目的提供的代码-
main.js
class Person {
constructor(fname, lname, age, address) {
this.fname = fname;
this.lname = lname;
this.age = age;
this.address = address;
}
get fullname() {
return this.fname + "-" + this.lname;
}
}
var a = new Person("Siya", "Kapoor", "15", "Mumbai");
var persondet = a.fullname;
目前,我们尚未向babel提供任何预设或插件详细信息。如果我们碰巧使用命令来转译代码-
npx babel main.js --out-file main_out.js
main_out.js
class Person {
constructor(fname, lname, age, address) {
this.fname = fname;
this.lname = lname;
this.age = age;
this.address = address;
}
get fullname() {
return this.fname + "-" + this.lname;
}
}
var a = new Person("Siya", "Kapoor", "15", "Mumbai");
var persondet = a.fullname;
我们将按原样获取代码。现在让我们将预设添加到.babelrc文件。
注意-在项目的根文件夹中创建.babelrc文件。
.babelrc for babel 6
.babelrc for babel 7
{
"presets":["@babel/env"]
}
我们已经安装了预设;现在让我们再次运行命令-
npx babel main.js --out-file main_out.js
main_out.js
"use strict";
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Person = function () {
function Person(fname, lname, age, address) {
_classCallCheck(this, Person);
this.fname = fname;
this.lname = lname;
this.age = age;
this.address = address;
}
_createClass(Person, [{
key: "fullname",
get: function get() {
return this.fname + "-" + this.lname;
}
}]);
return Person;
}();
var a = new Person("Siya", "Kapoor", "15", "Mumbai");
var persondet = a.fullname;
在ES6中,类语法如下
class Person {
constructor(fname, lname, age, address) {
this.fname = fname;
this.lname = lname;
this.age = age;
this.address = address;
}
get fullname() {
return this.fname + "-" + this.lname;
}
}
有构造函数,并且在其中定义了该类的所有属性。万一,我们需要在类之外定义类属性,而不能这样做。
class Person {
name = "Siya Kapoor";
fullname = () => {
return this.name;
}
}
var a = new Person();
var persondet = a.fullname();
console.log("%c"+persondet, "font-size:25px;color:red;");
如果碰巧编译以上代码,它将在babel中引发错误。这导致代码无法编译。
为了按照我们想要的方式工作,我们可以使用称为babel-plugin-transform-class-properties的babel插件。为了使其工作,我们需要首先按照以下方式安装它-
npm install --save-dev babel-plugin-transform-class-properties
npm install --save-dev @babel/plugin-proposal-class-properties
将插件添加到Babel 6的.babelrc文件中–
.babelrc for babel 7
{
"plugins": ["@babel/plugin-proposal-class-properties"]
}
现在,我们将再次运行该命令。
npx babel main.js --out-file main_out.js
main.js
class Person {
name = "Siya Kapoor";
fullname = () => {
return this.name;
}
}
var a = new Person();
var persondet = a.fullname();
console.log("%c"+persondet, "font-size:25px;color:red;");
编译为main_out.js
class Person {
constructor() {
this.name = "Siya Kapoor";
this.fullname = () => {
return this.name;
};
}
}
var a = new Person();
var persondet = a.fullname();
console.log("%c"+persondet, "font-size:25px;color:red;");
输出
以下是在浏览器中使用时得到的输出-
**是ES7中用于取幂的运算符。以下示例显示了ES7中相同功能的工作。它还显示了如何使用babeljs来转译代码。
let sqr = 9 ** 2;
console.log("%c"+sqr, "font-size:25px;color:red;");
要转换幂运算符,我们需要如下安装插件:
babel 6的软件包
npm install --save-dev babel-plugin-transform-exponentiation-operator
Babel 7软件包
npm install --save-dev @babel/plugin-transform-exponentiation-operator
将插件详细信息添加到.babelrc文件,如下所示,适用于babel 6-
{
"plugins": ["transform-exponentiation-operator"]
}
.babelrc for babel 7
{
"plugins": ["@babel/plugin-transform-exponentiation-operator"]
}
命令
npx babel exponeniation.js --out-file exponeniation_out.js
exponeniation_out.js
let sqr = Math.pow(9, 2);
console.log("%c" + sqr, "font-size:25px;color:red;");
输出
babel6和7中的插件所需的软件包如下-
npm install --save-dev babel-plugin-transform-es2015-for-of
npm install --save-dev @babel/plugin-transform-for-of
.babelrc for babel6
{
"plugins": ["transform-es2015-for-of"]
}
.babelrc for babel7
{
"plugins": ["@babel/plugin-transform-for-of"]
}
forof.js
let foo = ["PHP", "C++", "Mysql", "JAVA"];
for (var i of foo) {
console.log(i);
}
npx babel forof.js --out-file forof_es5.js
Forof_es5.js
let foo = ["PHP", "C++", "Mysql", "JAVA"];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var i = _step.value;
console.log(i);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
输出
babel6和7中的插件所需的软件包如下-
npm install --save-dev babel-plugin-transform-object-rest-spread
npm install --save-dev @babel/plugin-proposal-object-rest-spread
.babelrc for babel6
{
"plugins": ["transform-object-rest-spread"]
}
.babelrc for babel7
{
"plugins": ["@babel/plugin-proposal-object-rest-spread"]
}
o.js
let { x1, y1, ...z1 } = { x1: 11, y1: 12, a: 23, b: 24 };
console.log(x1);
console.log(y1);
console.log(z1);
let n = { x1, y1, ...z1};
console.log(n);
npx babel o.js --out-file o_es5.js
o_es5.js
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i]; for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
function _objectWithoutProperties(obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
let _x1$y1$a$b = { x1: 11, y1: 12, a: 23, b: 24 },
{ x1, y1 } = _x1$y1$a$b,
z1 = _objectWithoutProperties(_x1$y1$a$b, ["x1", "y1"]);
console.log(x1);
console.log(y1);
console.log(z1);
let n = _extends({ x1, y1 }, z1);
console.log(n);
输出
我们需要为babel 6安装以下软件包-
npm install --save-dev babel-plugin-transform-async-to-generator
npm install --save-dev @babel/plugin-transform-async-to-generator
.babelrc for babel 6
{
"plugins": ["transform-async-to-generator"]
}
.babelrc for babel 7
{
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
async.js
let timer = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("Promise resolved after 5 seconds");
}, 5000);
});
};
let out = async () => {
let msg = await timer();
console.log(msg);
console.log("hello after await");
};
out();
npx babel async.js --out-file async_es5.js
async_es5.js
function _asyncToGenerator(fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
} if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
},
function (err) {
step("throw", err); });
}
} return step("next");
});
};
}
let timer = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve("Promise resolved after 5 seconds");
}, 5000);
});
};
let out = (() => {
var _ref = _asyncToGenerator(function* () {
let msg = yield timer();
console.log(msg);
console.log("hello after await");
});
return function out() {
return _ref.apply(this, arguments);
};
})();
out();
我们必须使用polyfill,因为它不能在不支持promise的浏览器中使用。
输出