在浏览器中动态执行TypeScript [英] Dynamic execution of TypeScript in the browser

查看:757
本文介绍了在浏览器中动态执行TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有TypeScript,它可以异步下载另一个TypeScript/javascript模块:

I have TypeScript which asynchronously downloads another TypeScript/javascript module:

(function (exports) {
    "use strict";

    var path = require('path');

    exports.convertData = function (data) {
        return "converted " + data;
    }

})(typeof exports === 'undefined' ? this['converter.someConverter'] = {} : exports);

在执行主应用程序期间,我将此模块作为字符串接收,并且必须从那里使用函数 convertData .

During execution of my main app I receives this module as string and I have to use function convertData from there.

因此,我正在尝试以下操作:

So, I'm trying the following:

eval(rendererScript);
console.log(exports.convertData("some data"));

只有在删除 var path = require('path'); 的情况下,该方法才有效.否则,出现以下错误: 未捕获(承诺)错误:尚未为上下文_加载模块名称路径".使用require([])

It works well only in case if var path = require('path'); will be removed. Otherwise, the following error: Uncaught (in promise) Error: Module name "path" has not been loaded yet for context: _. Use require([])

问题:

  1. 在这种情况下可以使用eval()吗? (我们知道eval是邪恶的)
  2. 需要(路径)如何?我正在尝试使用 RequireJS ( http://requirejs.org /docs/node.html#2 ),但收到以下错误:未捕获的错误:路径"的脚本错误
  1. Is it OK to use eval() in this case? (as we know eval is evil)
  2. How to be with require('path')? I'm trying to use RequireJS (http://requirejs.org/docs/node.html#2) but receiving the following error: Uncaught Error: Script error for "path"

已编辑

因此,为了避免使用eval(),找到了以下解决方案:

So, in order to avoid eval() the following solution was found:

const scriptTag = document.createElement("script");
scriptTag.innerHTML = rendererScript;
document.body.appendChild(scriptTag);
this.m_rendererPlugin = (window as any)[`converter.someConverter`];

推荐答案

由于在您的情况下,输入代码是动态的,因此您可能需要在运行时使用TypeScript编译器API进行编译.如果您没有专用的服务器,可以 仍使用TypeScript编译器API在浏览器中编译TS项目 https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API .

Since in your case the input code is dynamic you need to compile at runtime probably using TypeScript compiler API. In the case you don't have a dedicated server for that, you can still compile TS projects in the browser using the TypeScript compiler API https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API .

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆