
loose mode 我翻译为松散模式,loose mode 在 babel 中通常是不推荐使用的,但是我们需要知道的是使用 loose mode 转换而来的代码更加像ES5的代码(更像是人手写的),大多数Babel插件都有两种模式 normal mode 和 loose mode,normal mode 转换而来的 ES5 代码更加符合 ECMAScript 6 的语义,而 loose mode 转换而来的代码更加简单,更像是人写的。
loose mode 的优点在于兼容旧引擎,可能会更加快,缺点在于如果我们需要将转换之后的代码重新转换为 native ES6 代码,可能会遇到问题,而这个冒险在大多数时候是不值得的。
以 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。

