首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型记录:如何导入源代码而不是文件

类型记录:如何导入源代码而不是文件
EN

Stack Overflow用户
提问于 2018-11-02 11:11:19
回答 1查看 248关注 0票数 0

我用这个片段:

代码语言:javascript
复制
  loadComponent(name) {
    var url = this.configurationService.configuration.api_url+"/generator/dynamic-loading/component/"+name;
    this.http.get(url, {responseType: 'text'}).subscribe(componentCode => {
      let result = ts.transpile(componentCode);
      console.log("### Component",result);
    });
  }

我喜欢“从结果中导入名字”

怎么可能呢?

EN

回答 1

Stack Overflow用户

发布于 2018-11-02 13:37:10

如果我正确理解,result是模块的JavaScript源代码(我将称之为“动态模块”),您希望加载该模块并访问其导出。假设允许动态模块导入一个固定的、很小的模块列表,则可能最容易将动态模块转换为CommonJS格式,并编写一个迷你模块加载器,该加载程序可以为eval的JavaScript源代码设置适当的上下文。

代码语言:javascript
复制
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;

如果动态模块的导入不限于预先知道的短列表,那么您的选项将取决于您在主项目中使用的模块绑定程序或加载程序。由于loadComponent已经是异步的,如果您的绑定器/加载程序支持动态导入,那么您可以将动态模块转换为AMD格式,并让您的迷你加载程序在加载其主体之前执行动态模块的所有依赖项的动态导入。可能有一些现有的库可以在这方面提供帮助,但我对它们并不熟悉;其他库应该可以随意添加有关它们的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53117495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档