想必每个写 JavaScript 的都或多或少了解过 ES5 引入的 严格模式 ,Babel 6 在把 ES6+ 代码转换为 ES5 时,也提供了「松散模式」(loose mode)的选项。Babel 的松散模式和 ES5 没有任何关系,这里提 ES5 严格模式只是在概念上作一个比对,方便理解 Babel 的松散模式。
两种模式
一些 Babel 插件有两种工作模式:
- 标准模式 :转换时尽可能遵循、接近 ES6 语义。
- 松散模式 :转换为简单的 ES5 实现。
松散模式的优、缺点显而易见:
- 优点 :转换出来的代码更简洁,没有为了接近 ES6 而添加的繁杂逻辑,文件更小,运行速度更快,兼容性更好。
- 缺点 :以后直接使用原生 ES6 时可能会遇到问题。需要留意。
一般而言,不建议使用松散模式,不过也可以综合考虑项目的复杂程度,结合实际做选择。
配置方式
可以直接使用 babel-preset-es2015-loose
:
{ "presets": [ "es2015-loose" ], }
具体到某个插件时,可以设置 loose
参数为 true
:
{ "plugins": [ ["transform-es2015-classes", {loose: true}], "transform-es2015-object-super" ] }
转换结果比较
以下面的代码为例:
class Person { constructor(name) { this.name = name; } sayHi() { return `Hi, this is ${this.name}`; } }
.babelrc
配置为标准模式时:
{ "presets": [ "es2015" ] }
转换以后的代码为:
"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(name) { _classCallCheck(this, Person); this.name = name; } _createClass(Person, [{ key: "sayHi", value: function sayHi() { return "Hi, this is " + this.name; } }]); return Person; }();
使用 loose preset 后:
{ "presets": [ "es2015-loose" ] }
转换结果为:
"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(name) { _classCallCheck(this, Person); this.name = name; } Person.prototype.sayHi = function sayHi() { return "Hi, this is " + this.name; }; return Person; }();
确实更像熟悉的 ES5 代码。
该如何选择,自己看着办咯。
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。