如何在节点项目中自动加载包含特定装饰器的文件

我已经在 Project A (主库)中创建了一个装饰器,并希望在应用程序在 Project B 中启动时自动加载所有这些装饰器(使用项目A)进行项目。反正有这样做吗?

index.ts 看起来像这样:

export function MyDecorator<T extends Controller>() {
  return (target: new () => T) => {
    // Do stuff with the decorator
  }
}

const server = http.createServer((req,res) => {

})
server.listen(8080)

是否可以执行项目B 中的所有类上的@MyDecorator()自动执行操作,而不必执行项目B

MyClass1.ts

import { MyDecorator } from 'project-a'

@MyDecorator()
export class ProjectBClass1 {}

MyClass2.ts

import { MyDecorator } from 'project-a'

@MyDecorator()
export class ProjectBClass2 {}
gehui19890302 回答:如何在节点项目中自动加载包含特定装饰器的文件

  • 我假设您的意思是按负载创建实例。
  • 我也不确定这是否是一个优雅的解决方案,但这是我的建议:

创建一个具有静态方法的类:

class ControllerCreator {
  private static constrollerInstances: any = []
  private static controllerConstructors : any = [];  

  static registerControllerClass(ctor: any) {
    ControllerCreator.controllerConstructors.push(ctor);
  }

  static createInstances() {
    ControllerCreator.controllerConstructors.forEach(
      ctor => constrollerInstances.push(new ctor()) // pushing them to static array to not lose
    )
  }
}

在装饰器中,您应该注册控制器构造器:

export function MyDecorator<T extends Controller>() {
  return (target: new () => T) => {
    // Do stuff with the decorator
    class newClass extends target {
      // ...
    }

    ControllerCreator.registerControllerClass(newClass);
  }
}

最后,您应该致电:

ControllerCreator.createInstances();
本文链接:https://www.f2er.com/2643069.html

大家都在问