是否可以在 Typescript 中装饰装饰器?

Is it possible to decorate a decorator in Typescript?

构建组件库,@Component 装饰器中有相当多的样板文件。例如样式和模板 url 始终是相同的相对路径。想知道是否可以使用装饰器将其干燥。

我想我可以编写一个装饰器来复制 @Component 功能的那些部分,但我希望利用现有的功能。

你当然可以扩展组件功能并抽象一些功能, 以下是基于

的解决方案

分量-metadata.ts

    import "reflect-metadata";
    import { ComponentMetadata } from "@angular/core";

    export function MyComponent(annotation: any): any {
      return function (target: Function) {
         let parentTarget = Object.getPrototypeOf(target.prototype).constructor;
         let parentAnnotations = Reflect.getMetadata("annotations", parentTarget);

         let parentAnnotation = parentAnnotations[0];
         Object.keys(parentAnnotation).forEach(key => {
           if (isPresent(parentAnnotation[key])) {
              annotation[key] = parentAnnotation[key];
           }
        });

        let fileName: string = annotation.moduleId.substring(0, annotation.moduleId.lastIndexOf("."));
        annotation["templateUrl"] = fileName + ".html";
        annotation["styleUrls"] = [fileName + ".css"];        
        let metadata: ComponentMetadata = new ComponentMetadata(annotation);

        Reflect.defineMetadata("annotations", [metadata], target);
     }
   }

假设 html 和 css 与组件定义在同一个文件夹中并且具有相同的名称,您可以根据需要进行更新。 例如

html : some.component.html

css : some.component.css

some.component.ts

   @MyComponent({
     selector: "some-component",
     moduleId: module.id 
   })
   export class SomeComponent{
      // Class implementation
   }