关于Babel 6的 loose mode

1.Overview

loose mode 我翻译为松散模式,loose mode在babel中通常是不推荐使用的,但是我们需要知道的是使用 loose mode 转换而来的代码更加像ES5的代码(更像是人手写的)

大多数Babel插件都有两种模式 normal modeloose modenormal mode 转换而来的ES5代码更加符合ECMAScript 6 的语义,而 loose mode 转换而来的代码更加简单,更像是人写的。

loose mode 的优点在于兼容旧引擎,可能会更加快,缺点在于如果我们需要将转换之后的代码重新转换为 native ES6 代码,可能会遇到问题,而这个冒险在大多数时候是不值得的。

2.Examples

以ES6的class为例,我们编写以下代码:

class person {
  constractor(name, age) {
    this.name = name;
    this.age = age;
  }
  getName(){
    return this.name;
  }
  getAge(){
  	  return this.age;
  }
}
复制代码

normal mode 下转换为:

"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() {
    _classCallCheck(this, person);
  }

  _createClass(person, [{
    key: "constractor",
    value: function constractor(name, age) {
      this.name = name;
      this.age = age;
    }
  }, {
    key: "getName",
    value: function getName() {
      return this.name;
    }
  }, {
    key: "getAge",
    value: function getAge() {
      return this.age;
    }
  }]);

  return person;
}();
复制代码

loose mode 下转换为:

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var person = function () {
  function person() {
    _classCallCheck(this, person);
  }

  person.prototype.constractor = function constractor(name, age) {
    this.name = name;
    this.age = age;
  };

  person.prototype.getName = function getName() {
    return this.name;
  };

  person.prototype.getAge = function getAge() {
    return this.age;
  };

  return person;
}();
复制代码

可以看到,非常直观的是 loose mode 下的代码更加像是人手写的。尽管如此,但是仍然不推荐使用 loose mode

References:

Babel 6: loose mode

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值