首页 > 解决方案 > How to import reflect-metadata correctly

问题描述

So I have a TypeScript project I am working on and I want to make use of the reflect-metadata package. I am a little confused about the correct way of importing this. It was my understanding that this only needed to be imported once in your "main" file. So in my case I have an app.ts in which I import reflect-metadata as the very first thing:

import 'reflect-metadata';

import ReflectionClass from '@src/Reflection/ReflectionClass';
...

ReflectionClass then in turn imports another class that eventually calls Reflect.getMetadata(). However, this fails with error

error TS2339: Property 'getMetadata' does not exist on type 'typeof Reflect'.

Only when I import reflect-metadata explicitly in the relevant file does the error disappear. Is this the correct way to do this? In other words, do I need to import reflect-metadata in each file that uses it as opposed to a global, one time import in your main file?

标签: typescriptreflect-metadata

解决方案


回答我自己的问题;是的,您只需导入一次。我做了一些整体项目重新安排,其中包括替换ts-node以获得基于汇总的解决方案并删除一堆未使用的包。之后,一个反射元数据的导入现在可以工作了。不幸的是,我无法推断出最初问题的确切原因,只能在重组后现在解决。也许其他一些软件包正在干扰它。


推荐阅读