![](/img/trans.png)
[英]Unknown plugin “transform-decorators-legacy” error when using react storybook in windows
[英]How to disable defining class properties in Babel + transform-decorators-legacy
在我的库中(针对AngularJS),我正在尝试实现以下功能:
Object.defineProperty
定义的getter替换。 但是我在巴别塔遇到了意外的举动。 在库中使用的Typescript中,它可以很好地工作,但是Babel创建了一堆代码,将已经定义的属性重新定义为其初始化程序。
这是ES2015中的修饰类:
@Component({
selector: 'test'
})
export class TestClass {
@Inject('$http') $http;
@Inject('$q') $q;
}
结果代码如下:
var TestClass = exports.TestClass = (_dec9 = (0, _ngMetasys.Component)({
selector: 'test'
}), _dec10 = (0, _ngMetasys.Inject)('$http'), _dec11 = (0, _ngMetasys.Inject)('$q'), _dec9(_class4 = (_class5 = function TestClass() {
(0, _classCallCheck3.default)(this, TestClass);
// everything is OK, TestClass.prototype.$http is a getter with function () => $http.
_initDefineProp(this, '$http', _descriptor5, this); // there are dragons. Property $http is redefined to undefined.
_initDefineProp(this, '$q', _descriptor6, this);
}, (_descriptor5 = _applyDecoratedDescriptor(_class5.prototype, '$http', [_dec10], {
enumerable: true,
initializer: null
}), _descriptor6 = _applyDecoratedDescriptor(_class5.prototype, '$q', [_dec11], {
enumerable: true,
initializer: null
})), _class5)) || _class4);
如何禁用此属性重新定义? 有什么方法可以避免重新定义babel的属性或替换它?
我想我已经找到了我问题的答案。 在babel-plugin-transform-decorators-legacy
有一个测试,它可以设置属性的描述符,甚至可以将简单的属性转换为吸气剂。
有一个限制。 如果您想记住装饰器以后再进行更改,它将无法正常工作。 我没有对其进行适当的调查,但是我认为我的问题是我在类(和属性)初始化之后更改了描述符,而对描述符所做的更改不会影响已经初始化的属性。
因此,有一个测试给了我提示。 是从这里来的 。
it('should support mutating an initialzer into an accessor', function(){
function dec(target, name, descriptor){
expect(target).to.be.ok;
expect(name).to.eql("prop");
expect(descriptor).to.be.an('object');
let {initializer} = descriptor;
delete descriptor.initializer;
delete descriptor.writable;
let value;
descriptor.get = function(){
if (initializer){
value = '__' + initializer.call(this) + '__';
initializer = null;
}
return value;
};
}
class Example {
@dec
prop = 3;
}
let inst = new Example();
expect(inst.prop).to.eql('__3__');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.