静下心来的个人专栏
上一篇

BabelJS - Babel 插件

广告
选中文字可对指定文章内容进行评论啦,→和←可快速切换按钮,绿色背景文字可以点击查看评论额。
大纲

BabelJS - Babel 插件

BabelJS 是一个 javascript 编译器,它可以根据可用的预设和插件更改代码的语法。 babel编译的流程涉及到以下3个部分:

  • parsing
  • transforming
  • printing

给 babel 的代码原样返回,只是语法改变了。我们已经看到将预设添加到 .babelrc 文件中以将代码从 es6 编译到 es5,反之亦然。预设只不过是一组插件。如果在编译期间没有提供预设或插件详细信息,Babel 将不会更改任何内容。

现在让我们讨论以下插件

  • transform-class-properties
  • Transform-exponentiation-operator
  • For-of
  • object rest and spread
  • async/await

现在,我们将创建一个项目设置并处理几个插件,这将清楚地了解 babel 中插件的要求。

npm init

我们必须安装 babel 所需的包——babel cli、babel core、babel-preset 等。

Packages for babel 6

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

Packages for babel 7

npm install @babel/cli @babel/core @babel/preset-env --save-dev

在你的项目中创建一个js文件并编写你的js代码。

 

Classes - Transform-class-properties

为此请看下面给出的代码

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 用于 babel 6

{
    "presets": [
        "es2015"
    ]
}

.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 插件。为了让它工作,我们需要先安装它,如下所示:

Packages for babel 6

npm install --save-dev babel-plugin-transform-class-properties

Package for babel 7

npm install --save-dev @babel/plugin-proposal-class-properties

Add the plugin to .babelrc file for babel 6 

.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;");

Compiled to 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;");

以下是我们在浏览器中使用时得到的输出

 

Exponentiation Operator - transform-exponentiation-operator

** 是 ES7 中用于求幂的运算符。以下示例显示了 ES7 中相同的工作方式。它还展示了如何使用 babeljs 转译代码。

let sqr = 9 ** 2;
console.log("%c"+sqr, "font-size:25px;color:red;");

要转换幂运算符,我们需要安装一个插件,如下所示:

Packages for babel 6

npm install --save-dev babel-plugin-transform-exponentiation-operator

Packages for 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;");

输出

For-of

babel6和7中的插件需要的包如下:

Babel6

npm install --save-dev babel-plugin-transform-es2015-for-of

Babel 7

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;
      }
   }
}

输出

object rest spread

babel6和7中的插件需要的包如下

Babel 6

npm install --save-dev babel-plugin-transform-object-rest-spread

Babel 7

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);

输出

async/await

我们需要为 babel 6 安装以下包

npm install --save-dev babel-plugin-transform-async-to-generator

Packages for babel 7

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 的浏览器中不起作用。

输出

版权声明:著作权归作者所有。

X

欢迎加群学习交流

联系我们