@babel/plugin-proposal-class-pro

2023-05-09  本文已影响0人  侯工

@babel/plugin-proposal-class-properties

这个插件主要作用是用来编译类的。通常在webpack下配置的babel.config.js的内容如下

module.exports = {
  presets: [ "@babel/preset-env", "@babel/preset-react" ],
  plugins: [ 
    "@babel/plugin-transform-arrow-functions",  // 这个是箭头函数的处理
    ["@babel/plugin-proposal-decorators", {"legacy": true}], // 这个是装饰器
    ["@babel/plugin-proposal-class-properties", { "loose": false }],  // 这里是关键
  ]
}

我们可以看到,{ "loose": false } 这个参数,这个参数会影响什么呢?看下面
没参数编译结果(默认{loose:false}):


var Bork = function Bork() {
  babelHelpers.classCallCheck(this, Bork)
  Object.defineProperty(this, 'x', { configurable: true, enumerable: true, writable: true, value: 'bar' })
  Object.defineProperty(this, 'y', { configurable: true, enumerable: true, writable: true, value: void 0 })
}
Object.defineProperty(Bork, 'a', { configurable: true, enumerable: true, writable: true, value: 'foo' })
Object.defineProperty(Bork, 'b', { configurable: true, enumerable: true, writable: true, value: void 0 })

有参数{loose:true}编译结果:

var Bork = function Bork() {
  babelHelpers.classCallCheck(this, Bork)
  this.x = 'bar'
  this.y = void 0
}
Bork.a = 'foo'
Bork.b = void 0

那么上面两个有什么区别呢? 其实最大的却别就是,类编译后,对属性的定义不同。
loose=false时,是使用Object.defineProperty定义属性,loose-ture,则使用赋值法直接定义,那么属性定义与赋值有什么却别呢?

这个问题就复杂了,简单说一下吧。

上一篇 下一篇

猜你喜欢

热点阅读