It seems like the variable result
contains the JavaScript source code of a module, referred to as the "dynamic module," and you aim to load this module to access its exports. Assuming there is a predefined set of modules that the dynamic module can import, the easiest approach would be to transpile the dynamic module into CommonJS format and create a small module loader to properly configure the context for evaluating the JavaScript code using eval
.
function evalCommonjsModule(moduleSource: string, requireMap: Map<string, {}>) {
let moduleFunc = eval("(module, exports, require) => {" + moduleSource + "}");
let module = {exports: {}};
moduleFunc(module, module.exports, (requireName) => {
let requireModule = requireMap.get(requireName);
if (requireModule === undefined)
throw new Error(`Attempted to require(${requireName}), which was not in requireMap`);
return requireModule;
});
return module.exports;
}
import * as AllowedImport1 from "allowed-import-1";
import * as AllowedImport2 from "allowed-import-2";
// In loadComponent:
// Example from https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-simple-transform-function
let result = ts.transpileModule(componentCode, {
compilerOptions: { module: ts.ModuleKind.CommonJS }
});
let resultModule = evalCommonjsModule(result, new Map([
["allowed-import-1", AllowedImport1],
["allowed-import-2", AllowedImport2]
]));
let name = resultModule.name;
If the dynamic module's imports are not limited to a predefined list, your options will rely on the main project's module bundler or loader capabilities. If your bundler/loader supports dynamic imports and since loadComponent
is already asynchronous, consider transpiling the dynamic module into AMD format and have your mini-loader handle dynamic imports of all dependencies before loading its content. There might be existing libraries that can assist with this process, but I'm not well-versed in them; others are encouraged to share relevant information.