2
In a web project with TypeScript
, using modules commonjs
, compiled via Webpack (version 5), I need to call classes and methods dynamically from type variables string
containing their names.
I can separate these files that will be used "globally" through folders or with a differentiated extension. In the latter case, 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 do INCLUDE, Webpack makes classes inaccessible.
When I do not INCLUDE, Webpack does not insert the classes into
bundle.js
In this project the return of the API is processed by a module (ES6 / commonjs), and there will be times when the API will return which Javascript class/method should be run in the Browser. Thus, the class and method name will be known from variables of the string type.
As an example, I have the following scenario:
- main.ts: entrypoint
- Mymodule.ts: module that makes the AJAX calls, receives the return and calls the method returned by the API.
- Myglobal.glob.ts: Class with example of one of the methods that can be called by callback from
MyModule.ts
Filing cabinet main.ts
:
import { MyModule } from './MyModule';
MyModule.callApi();
Filing cabinet MyModule.ts
:
import { MyGlobal } from './MyGlobal.glob';
export class MyModule {
public static callApi() {
/**
* Este método faz uma chamada AJAX
* E passa JSON do retorno para o callback
*/
let retorno = {
class: 'MyGlobal',
method: 'bar',
};
this.callback(retorno);
}
public static callback(retorno: any) {
eval(retorno.class + '.' + retorno.method + '();');
}
}
Filing cabinet MyGlobal.glob.ts
:
export class MyGlobal {
public static foo() {
return 1;
}
public static bar() {
return 2;
}
}
When executing the above code, I have 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, and after compiled by webpack these "original names of classes/methods" are inaccessible?