如何通过Babel在类实例上使用JavaScript装饰器?
给定以下如何通过Babel在类实例上使用JavaScript装饰器?,javascript,babeljs,decorator,Javascript,Babeljs,Decorator,给定以下.babelrc配置: { "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": false, "decoratorsBeforeExport": false }] ] } 我无法让班级装饰师工作: @annotation class MyClass { } function annotation(target) { target.annotated = tr
.babelrc
配置:
{
"plugins": [
["@babel/plugin-proposal-decorators", {
"legacy": false,
"decoratorsBeforeExport": false
}]
]
}
我无法让班级装饰师工作:
@annotation
class MyClass { }
function annotation(target) {
target.annotated = true;
}
const c = new MyClass();
console.log(c);
另外,console.log(target)
会产生以下结果:
对象[描述符]{kind:'class',元素:[]}
对于console.log(c)
语句,我希望看到添加了注释的属性,但是我得到的只是MyClass{}
一些额外的澄清-我知道legacy:true
标志,但我希望按照现在的样子使用规范,而不使用legacy回退。我做了一些额外的研究,我认为我走的是正确的道路,下面是更新的代码:
@annotation
class MyClass { }
function annotation(descriptor) {
const {
kind,
elements
} = descriptor;
const newElements = elements.concat([{
kind: 'field',
placement: 'own',
descriptor: {
annotated: true
}
}]);
return {
kind,
elements: newElements
}
}
const c = new MyClass();
console.log(c);
以上这些仍然不起作用,但至少我不再犯奇怪的错误:)
如果有兴趣,请阅读已接受答案上的评论,查看一些可能的解决方案
**更新**
实际上,我成功地找到了答案——使用legacy:false
选项:
@annotation
class MyClass { }
function annotation(descriptor) {
const {
kind,
elements
} = descriptor;
const newElements = elements.concat([{
kind: 'field',
placement: 'own',
key: 'annotated',
initializer: () => true,
descriptor: {
configurable: true,
writable: true,
enumerable: true
}
}]);
return {
kind,
elements: newElements
}
}
const c = new MyClass();
console.log(c); // MyClass { annotated: true }
返回在构造函数中设置属性的新类
@注释
类MyClass{}
函数注释(目标){
返回类扩展了目标{
构造函数(…参数){
超级(…args);
this.annotated=true;
}
}
}
const c=新的MyClass();
控制台日志(c);
上述返回“类扩展值”不是构造函数或null”。@Tamas-Hmm…可能与不使用旧的装饰器有关。最新的提案有很多复杂之处。@Tamas FWIW如果你不是一成不变的话,支持该提案的人建议现在就使用这个遗产decorators champion group建议继续使用Babel“legacy”decorators或TypeScript“experimental”decorators。
是的,我同意你关于复杂性的观点。。。我想我已经接近一个解决方案了,但它仍然不起作用。我将用更多的信息更新我的原始问题我只是在试验,所以这不是什么大问题,但我真的很想知道如何使用新规范,使用legacy:false
感谢这个人,当使用这个非legacy decorators时,是否有一种方法可以将注释的
属性设置为true
添加到MyClass
构造函数类本身,就像您使用传统装饰器一样(即不创建MyClass
的实例)?例如:console.log(MyClass.annotated);//是否正确
?另外,是否有办法区分装饰器是否与遗留API和非遗留API一起使用?非常感谢。当“legacy”:false,“decoratorsBeforeExport”:false
时,说明如何使用descriptor.elements
属性的规范或教程在哪里找到的?谢谢大家!@坦白说,我不记得了。很可能这是一个GH问题/某种讨论,但我不能给你一个确切的链接,我很抱歉。找到了你的这篇文章:我明天去看看!无论如何谢谢你!哦,还有。。。(脸掌)哈哈:)