2017-07-26 55 views
3

我想在我的一个项目中使用Typescript装饰器,但我遇到了一个奇怪的行为,我无法理解。Typescript装饰只能在相同的方法内工作

似乎只工作,如果装饰类是试图获取元数据相同的方法中:

describe('metadata tests',() => { 

    it('should retrieve metadata',() => { 

     class Test { 
      @TestDecorator('some value') 
      property: string; 
     } 

     const metadata = Reflect.getMetadata('test', new Test(), 'property'); 
     expect(metadata).toEqual('some value'); //Passes 
    }); 

}); 

但只要我移动它的方法以外,它不工作了:

describe('metadata tests',() => { 

    class Test { 
     @TestDecorator('some value') 
     property: string; 
    } 

    it('should retrieve metadata',() => { 
     const metadata = Reflect.getMetadata('test', new Test(), 'property'); 
     expect(metadata).toEqual('some value'); //Fails 
    }); 

}); 

这两项测试都采用这种测试装饰:

function TestDecorator(value: any) { 
    return function (target: any, propertyKey: string) { 
     console.log(`I'm being decorated!`); 
     Reflect.defineMetadata('test', value, target, propertyKey); 
    }; 
} 

无一不是首席婷到控制台...

此外,双方transpiled代码中,我可以看到的财产被正确和准确的装饰以同样的方式:

var Test = (function() { 
    function Test() { 
    } 
    __decorate([ 
     TestDecorator('some value'), 
     __metadata("design:type", String) 
    ], Test.prototype, "property", void 0); 
    return Test; 
}()); 

在这里,这是我的tsconfig.json。我相信这是正确的(es5emitDecoratorMetadataexperimentalDecorators):

{ 
    "compilerOptions": { 
    "module": "commonjs", 
    "target": "es5", 
    "declaration": true, 
    "outDir": "dist", 
    "moduleResolution": "node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "removeComments": true 
    }, 
    "exclude": [ 
    "node_modules", 
    "dist" 
    ] 
} 

我缺少什么?

回答

0

对于那些同样的问题,我不认为这是一个解决方案,但在我的情况下,从Webpack切换到Rollup.js解决了这个问题...