美文网首页
@babel/plugin-proposal-class-pro

@babel/plugin-proposal-class-pro

作者: 侯工 | 来源:发表于2023-05-09 11:16 被阅读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,则使用赋值法直接定义,那么属性定义与赋值有什么却别呢?

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

  • 赋值就是,常见的,用得最多的方法 this.a='abc' 就是赋值,定义就是需要使用Object.defineProperty方法对属性进行定义。 使用赋值时,是可能会触发属性的setter方法的。
  • 定义法,就是完整的定义一个属性,可以定义属性的可读性、可写性、setter、getter等

相关文章

网友评论

      本文标题:@babel/plugin-proposal-class-pro

      本文链接:https://www.haomeiwen.com/subject/fvtlsdtx.html