babel插件
上节课补充:@babel/polyfill 已过时,目前被
core-js
和generator-runtime
所取代
除了预设可以转换代码之外,插件也可以转换代码,它们的顺序是:
- 插件在 Presets 前运行。
- 插件顺序从前往后排列。
- Preset 顺序是颠倒的(从后往前)。
通常情况下,@babel/preset-env
只转换那些已经形成正式标准的语法,对于某些处于提案早期阶段、还没有确定的语法不做转换。
如果要转换这些语法,就要单独使用插件,下面随便列举一些插件。
@babel/plugin-proposal-class-properties
该插件可以让你在类中书写初始化字段
{
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
class A {
a = 1;
constructor(){
this.b = 3;
}
}
编译后
function _defineProperty(e, r, t) {
return (
(r = _toPropertyKey(r)) in e
? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0,
})
: (e[r] = t),
e
)
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string")
return "symbol" == typeof i ? i : i + ""
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t
var e = t[Symbol.toPrimitive]
if (void 0 !== e) {
var i = e.call(t, r || "default")
if ("object" != typeof i) return i
throw new TypeError("@@toPrimitive must return a primitive value.")
}
return ("string" === r ? String : Number)(t)
}
class A {
constructor() {
_defineProperty(this, "a", 1)
this.b = 3
}
}
此插件功能貌似已经集成到预设中。
@babel/plugin-proposal-function-bind
该插件可以让你轻松的为某个方法绑定 this。
{
"plugins": [
"@babel/plugin-proposal-function-bind"
]
}
function Print() {
console.log(this.loginId);
}
const obj = {
loginId: "abc"
};
obj::Print(); //相当于:Print.call(obj);
编译后
function Print() {
console.log(this.loginId)
}
const obj = {
loginId: "abc",
}
Print.call(obj) //相当于:Print.call(obj);
遗憾的是,目前 vscode 无法识别该语法,会在代码中报错,虽然并不会有什么实际性的危害,但是影响观感
@babel/plugin-proposal-optional-chaining
转换赋值表达式左侧的可选链。
{
"plugins": [
"@babel/plugin-proposal-optional-chaining"
]
}
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
编译后
var _obj$foo, _obj$foo$bar, _obj$qux
const obj = {
foo: {
bar: {
baz: 42,
},
},
}
const baz =
obj === null || obj === void 0
? void 0
: (_obj$foo = obj.foo) === null || _obj$foo === void 0
? void 0
: (_obj$foo$bar = _obj$foo.bar) === null || _obj$foo$bar === void 0
? void 0
: _obj$foo$bar.baz // 42
const safe =
obj === null || obj === void 0
? void 0
: (_obj$qux = obj.qux) === null || _obj$qux === void 0
? void 0
: _obj$qux.baz // undefined
此插件功能貌似已经集成到预设中。
babel-plugin-transform-remove-console
该插件会移除源码中的控制台输出语句。
{
"plugins": [
"babel-plugin-transform-remove-console"
]
}
console.log("foo");
console.error("bar");
编译后
@babel/plugin-transform-runtime
在使用 babel 时会提供一些公共的 API,这些 API 会帮助代码转换,而用到这些 API 的地方都会注入这些代码,就会导致代码重复,所以可以使用 @babel/plugin-transform-runtime
帮我们将公共 API 抽离成公共库。