huruji / blog

红日初升,其道大光:sun_with_face::house_with_garden:请star或watch,不要fork
https://juejin.im/user/5894886f2f301e00693a3e49/posts
158 stars 11 forks source link

关于Babel 6的 loose mode #42

Open huruji opened 6 years ago

huruji commented 6 years ago

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