我有一个TypeScript,它异步下载另一个类型记录/javascript模块:
(function (exports) {
"use strict";
var path = require('path');
exports.convertData = function (data) {
return "converted " + data;
}
})(typeof exports === 'undefined' ? this['converter.someConverter'] = {} : exports);
在执行我的主应用程序时,我会以字符串的形式接收这个模块,我必须从那里使用函数convertData。
所以,我在尝试以下几点:
eval(rendererScript);
console.log(exports.convertData("some data"));
只有当var path = require('path');将被删除时,它才能正常工作。否则,以下错误:Uncaught (承诺)错误:模块名"path“尚未为上下文加载:_。使用要求([])
问题:
编辑的
因此,为了避免eval(),找到了以下解决方案:
const scriptTag = document.createElement("script");
scriptTag.innerHTML = rendererScript;
document.body.appendChild(scriptTag);
this.m_rendererPlugin = (window as any)[`converter.someConverter`];
发布于 2018-10-25 03:52:24
因为在您的示例中,输入代码是动态的,所以您需要在运行时编译,很可能使用TypeScript编译器API。在没有专用服务器的情况下,仍然可以使用TypeScript编译器API https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API在浏览器中编译TS项目。
对于transpiling,您不必做任何事情,只需在html中包含node_modules/typescript/ypescript.js,就可以完成了。但是对于更复杂的API,如类型检查和语言服务API (https://github.com/Microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin),您需要实现一些接口。
https://stackoverflow.com/questions/46059313
复制相似问题