Home > Mobile >  How to reference the current module in Typescript
How to reference the current module in Typescript

Time:11-27

If I import an external module I can reference items in that module via the module variable from the import.

import * as foo from 'foo';

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

But how do I get a reference to the current module context if I want to do something similar?

const thisModule = ???;

thisModule[`fn`]();

CodePudding user response:

It looks like a dumb thing to do, but you can import the file info itself:

File: foo.ts

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

import * as self from './foo';

self.foo();

CodePudding user response:

Exploring this further I tried something that I didn't think would work, but it did! The following solution includes a self-referential import which gives me a variable reference to the module.

In filename 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]();

If anyone knows of a more canonical way of accomplishing this I would appreciate the feedback.

  • Related