如何在Typescript中引用当前模块

oknrviil  于 2022-12-01  发布在  TypeScript
关注(0)|答案(2)|浏览(136)

如果我导入一个外部模块,我可以通过导入的模块变量引用该模块中的项目。

import * as foo from 'foo';

foo.fn()
foo['fn']()

但是,如果我想做类似的事情,如何获得对当前模块上下文的引用呢?

const thisModule = ???;

thisModule[`fn`]();
kcwpcxri

kcwpcxri1#

这看起来像是一件愚蠢的事情,但你可以导入文件信息本身:
档案:foo.ts

export function foo() {
    console.log('foo');
}

import * as self from './foo';

self.foo();
wswtfjt7

wswtfjt72#

进一步探索这个问题,我尝试了一些我认为不可行的方法,但是它成功了!下面的解决方案包括一个自引用导入,它为我提供了一个对模块的变量引用。
在文件名foo.ts中

import * as local from './foo';

export function fn() {
    console.log('fn()');
}

export class bar {
    constructor() {
        console.log('bar');
    }
}

local['fn']();
new local['bar']();

// if using a variable
const c = 'bar';
new (<any>local>)[c]();

如果有人知道一个更规范的方法来完成这一点,我将感谢反馈。

相关问题