In a web project with TypeScript, using commonjs modules, compiled through Webpack (version 5), I need to call classes and methods dynamically from string variables containing their names.
I can separate those files that will be used "globally" through folders or with a different extension. As a last resort, I can even create an index file to manually include all the files that need to be accessed this way.
The problem is that:
When I use
INCLUDE
, the Webpack makes the classes inaccessible.When I don't use
INCLUDE
, Webpack doesn't insert the classes in bundle.js
In this project the API return is processed by a module (ES6 / commonjs), and there will be times when the API will return which JavaScript class/method should be executed in the Browser. This way, the name of the class and the method will be known from variables of type string.
As an example, I have the following scenario:
- main.ts: entrypoint.
- MyModule.ts: module that makes AJAX calls, receives the return and calls the method returned by the API.
- MyGlobal.glob.ts: Class with an example of one of the methods that can be called by the
MyModule.ts
callback.
File main.ts
:
import { MyModule } from './MyModule';
MyModule.callApi();
File MyModule.ts
:
import { MyGlobal } from './MyGlobal.glob';
export class MyModule {
public static callApi() {
/**
* This method makes an AJAX call
* and passes the return JSON to the callback
*/
let my_return = {
class: 'MyGlobal',
method: 'bar',
};
this.callback(my_return);
}
public static callback(my_return: any) {
classes[my_return.class][my_return.method]();
}
}
File MyGlobal.glob.ts
:
export class MyGlobal {
public static foo() {
return 1;
}
public static bar() {
return 2;
}
}
When running the code above, I get the following error:
> Uncaught ReferenceError: MyGlobal is not defined
> at eval (eval at callback (main.js:1), <anonymous>:1:1)
> at Function.callback (main.js:1)
> at Function.callApi (main.js:1)
> at main.js:1
> at main.js:1
How to call these methods, from strings, when, after compiled by the webpack, these "original class/method names" are inaccessible?
I greatly appreciate any help! Thanks a lot!