node/typescript:如何确保有副作用的导入是运行?

node/typescript: how to ensure imports with side effects are run?

我正在用打字稿写一个节点应用程序。我写了一个 class 装饰器 @myDecorator@myDecorator 的目的是我需要跟踪它所应用的所有 classes。

我的问题:如何确保在使用该行为之前加载所有那些装饰过的 classes?一些示例代码将有助于使这个更具体:

  1. 文件 myDecorator.ts 中装饰器的声明:
type ConstructorType = { new (...args: any[]): any };

// keep track of decorated classes
const registeredClasses: Map<string, ConstructorType> = new Map();

// class decorator
export function myDecorator<T extends ConstructorType>(targetConstructor: T) {
  // create the modified class
  const newClass = class extends targetConstructor { /* ... */ }
  // register the modified class
  registeredClasses.set(targetConstructor.name, newClass);
  // and return it
  return newClass;
}

export function doSomethingWithMyDecoratedClasses() {
  //... some behavior that relies on `registeredClasses`
}
  1. 在文件 someClass.ts
  2. 中修饰 class 的声明
import {myDecorator} from 'myDecorator.ts'

@myDecorator
class SomeClass { /* ... */ }
  1. anotherFile.ts 中使用 doSomethingWithMyDecoratedClasses:
import { doSomethingWithMyDecoratedClasses } from 'myDecorator.ts`
//...
doSomethingWithMyDecoratedClasses()
//...

问题是在调用 doSomethingWithMyDecoratedClasses 之前,我需要确保 SomeClass 已添加到 registeredClasses。而且,事实上,我已经在我的应用程序中编写了很多这样的 classes,我需要确保它们都已注册。

我目前最好的理解是我需要在anotherFile.ts中调用import 'someClass.ts'(事实上,导入所有文件,其中装饰classes 已声明),所以我真的需要 import someClass1.tsimport someClass2.ts、...

这是best/only的方法吗?有推荐的模式吗?

大多数应用程序都有一个索引文件,负责导入顶级内容。如果您在那里导入 doSomethingWithMyDecoratedClasses,您将保证首先导入其他所有内容。

另一种方法是不在模块的根级别调用它,而是等待事件。