“targets”: {
“browsers”: [“> 1%”, “last 2 versions”, “not ie <= 9”]
}
- loose
可以直译为“松散模式”,默认为false
,即为normal
模式。简单地说,就是normal
模式转换出来的代码更贴合ES6
风格,更严谨;而loose
模式更像我们平时的写法。以class
写法举例:
我们先写个简单的class
:
class TestBabelLoose {
constractor(name) {
this.name = name
}
getName() {
return this.name
}
}
new TestBabelLoose(‘Tusi’)
使用normal
模式编译得到结果如下:
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(“Cannot call a class as a 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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var TestBabelLoose =
/#PURE/
function () {
function TestBabelLoose() {
_classCallCheck(this, TestBabelLoose);
}
_createClass(TestBabelLoose, [{
key: “constractor”,
value: function constractor(name) {
this.name = name;
}
}, {
key: “getName”,
value: function getName() {
return this.name;
}
}]);
return TestBabelLoose;
}();
new TestBabelLoose(‘Tusi’);
而使用loose
模式编译得到结果是这样的,是不是更符合我们用prototype
实现类的写法?
“use strict”;
var TestBabelLoose =
/#PURE/
function () {
function TestBabelLoose() {}
var _proto = TestBabelLoose.prototype;
_proto.constractor = function constractor(name) {
this.name = name;
};
_proto.getName = function getName() {
return this.name;
};
return TestBabelLoose;
}();
new TestBabelLoose(‘Tusi’);
个人推荐配置loose: false
,当然也要结合项目实际去考量哪种模式更合适。
- modules
可选值有:"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false
,默认是auto
该配置将决定是否把ES6
模块语法转换为其他模块类型。注意,cjs
是commonjs
的别名。
其实我一直有个疑惑,为什么我看到的开源组件中,基本都是设置的modules: false
?后面终于明白了,原来这样做的目的是把转换模块类型的处理权交给了webpack
,由webpack
去处理这项任务。所以,如果你也使用webpack
,那么设置modules: false
就没错啦。
- useBuiltIns
可选值有:"entry" | "usage" | false
,默认是false
该配置将决定@babel/preset-env
如何去处理polyfill
"entry"
如果useBuiltIns
设置为"entry"
,我们需要安装@babel/polyfill
,并且在入口文件引入@babel/polyfill
,最终会被转换为core-js
模块和regenerator-runtime/runtime
。对了,@babel/polyfill
也不会处理stage <=3
的提案。
我们用一段包含了Promise
的代码来做下测试:
import “@babel/polyfill”;
class TestBabelLoose {
constractor(name) {
this.name = name
}
getName() {
return this.name
}
testPromise() {
return new Promise(resolve => {
resolve()
})
}
}
new TestBabelLoose(‘Tusi’)
但是编译后,貌似引入了很多polyfill
啊,一共149个,怎么不是按需引入呢?嗯…你需要往下看了。
import “core-js/modules/es6.array.map”;
import “core-js/modules/es6.map”;
import “core-js/modules/es6.promise”;
import “core-js/modules/es7.promise.finally”;
import “regenerator-runtime/runtime”;
// 此处省略了144个包。。。
"usage"
如果useBuiltIns
设置为"usage"
,我们无需安装@babel/polyfill
,babel
会根据你实际用到的语法特性导入相应的polyfill
,有点按需加载的意思。
// 上个例子中,如果改用useBuiltIns: ‘usage’,最终转换的结果,只有四个模块
import “core-js/modules/es6.object.define-property”;
import “core-js/modules/es6.promise”;
import “core-js/modules/es6.object.to-string”;
import “core-js/modules/es6.function.name”;
配置"usage"
时,常搭配corejs
选项来指定core-js
主版本号
useBuiltIns: “usage”,
corejs: 3
false
如果useBuiltIns
设置为false
,babel
不会自动为每个文件加上polyfill
,也不会把import "@babel/polyfill"
转为一个个独立的core-js
模块。
@babel/preset-env
还有一些配置,自己慢慢去折腾吧…
stage-x
stage-x
描述的是ECMA
标准相关的内容。根据TC39
(ECMA
39号技术专家委员会)的提案划分界限,stage-x
大致分为以下几个阶段:
-
stage-0:
strawman
,还只是一种设想,只能由TC39
成员或者TC39
贡献者提出。 -
stage-1:
proposal
,提案阶段,比较正式的提议,只能由TC39
成员发起,这个提案要解决的问题须有正式的书面描述,一般会提出一些案例,以及API
,语法,算法的雏形。 -
stage-2:
draft
,草案,有了初始规范,必须对功能的语法和语义进行正式描述,包括一些实验性的实现,也可以提出一些待办事项。 -
stage-3:
condidate
,候选,该提议基本已经实现,需要等待实践验证,用户反馈及验收测试通过。 -
stage-4:
finished
,已完成,必须通过Test262
验收测试,下一步就是纳入到ECMA
标准中。比如一些ES2016
,ES2017
的语法就是通过这个阶段被合入ECMA
标准中了。
有兴趣了解的可以关注ecma262。
需要注意的是,babel@7已经移除了stage-x的preset,stage-4部分的功能已经被@babel/preset-env集成了,而如果你需要stage <= 3部分的功能,则需要自行通过plugins组装。
As of v7.0.0-beta.55, we’ve removed Babel’s Stage presets.
Please consider reading our blog post on this decision at
https://babeljs.io/blog/2018/07/27/removing-babels-stage-presets
for more details. TL;DR is that it’s more beneficial in the long run to explicitly add which proposals to use.
If you want the same configuration as before:
{
“plugins”: [
// Stage 2
[“@babel/plugin-proposal-decorators”, { “legacy”: true }],
“@babel/plugin-proposal-function-sent”,
“@babel/plugin-proposal-export-namespace-from”,
“@babel/plugin-proposal-numeric-separator”,
“@babel/plugin-proposal-throw-expressions”,
// Stage 3
“@babel/plugin-syntax-dynamic-import”,
“@babel/plugin-syntax-import-meta”,
[“@babel/plugin-proposal-class-properties”, { “loose”: false }],
“@babel/plugin-proposal-json-strings”
]
}
自己写preset
如需创建一个自己的preset
,只需导出一份配置即可,主要是通过写plugins
来实现preset
。此外,我们也可以在自己的preset
中包含第三方的preset
。
module.exports = function() {
return {
// 增加presets项去包含别人的preset
presets: [
require(“@babel/preset-env”)
],
// 用插件来包装成自己的preset
plugins: [
“pluginA”,
“pluginB”,
“pluginC”
]
};
}
=================================================================================
babel
运行时,很重要的一个东西,它一定程度上决定了你产出的包的大小!一般适合于组件库开发,而不是应用级的产品开发。
这里有两个东西要注意,一个是@babel/runtime
,它包含了大量的语法转换包,会根据情况被按需引入。另一个是@babel/plugin-transform-runtime
,它是插件,负责在babel
转换代码时分析词法语法,分析出你真正用到的ES6+
语法,然后在transformed code
中引入对应的@babel/runtime
中的包,实现按需引入。
举个例子,我用到了展开运算符...
,那么经过@babel/plugin-transform-runtime
处理后的结果是这样的:
/* 0 */
/***/ (function(module, exports, webpack_require) {
var arrayWithoutHoles = webpack_require(2);
var iterableToArray = webpack_require(3);
var nonIterableSpread = webpack_require(4);
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray;
// EXTERNAL MODULE: …/node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = webpack_require(0);
var toConsumableArray_default = /#PURE/webpack_require.n(toConsumableArray);
@babel/runtime
是需要按需引入到生产环境中的,而@babel/plugin-transform-runtime
是babel
辅助插件。因此安装方式如下:
npm i --save @babel/runtime
npm i --save-dev @babel/plugin-transform-runtime
配置时也挺简单:
const buildConfig = {
presets: [
// …
],
plugins: [
“@babel/plugin-transform-runtime”
],
// …
}
@babel/runtime和useBuiltIns: 'usage’有什么区别?
两者看起来都实现了按需加载的能力,但是实际上作用是不一样的。@babel/runtime
处理的是语法支持,把新的语法糖转为目标环境支持的语法;而useBuiltIns: 'usage'
处理的是垫片polyfill
,为旧的环境提供新的全局对象,如Promise
等,提供新的原型方法支持,如Array.prototype.includes
等。如果你开发的是组件库,一般不建议处理polyfill
的,应该由调用者去做这些支持,防止重复的polyfill
。
- 开发组件时,如果仅使用
@babel/plugin-transform-runtime
- 加上
useBuiltIns: 'usage'
,多了很多不必要的包。
================================================================================
最后简单地提一下使用babel@7
要注意的地方,当然更详细的内容还是要看babel官方。
babel@7
相关的包命名都改了,基本是@babel/plugin-xxx
,@babel/preset-xxx
这种形式。这是开发插件体系时一个比较标准的命名和目录组织规范。