【问题标题】:Load TypeScript module from string in memory?从内存中的字符串加载 TypeScript 模块?
【发布时间】:2019-04-25 17:18:58
【问题描述】:
function requireFromString(src, filename) {
  var Module = module.constructor;
  var m = new Module();
  m._compile(src, filename);
  return m.exports;
}

console.log(requireFromString(`
  const a = require('./a');
  const fs = require('fs');
  module.exports = { test: a}
`));

我们可以通过这个来 require 节点模块。

我们可以在内存中要求 TypeScript 模块吗?

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    我想你在看什么:How to compile TypeScript code in the browser?

    或者只使用 typescriptServices.js:

         <script src="https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js"></script>
    

    并添加js代码:

       var hello = "test";
       var js = ts.transpile("let a = `<div>${hello}</div>`");
       console.log(js);
       eval(js);
       console.log(a);
    

    ts.transpile 将 ts 翻译成 js 字符串。

    Examle on next.plnkr.co.

    【讨论】:

    • 我想在运行时导入一些模块?喜欢import * as foo from 'a.ts'
    • 在输出中,您将获得必要的javascript,但您应该自己控制模块,使用babeljs.io
    【解决方案2】:

    我认为您正在寻找的是所谓的动态导入。查看https://blog.mariusschulz.com/2018/01/14/typescript-2-4-dynamic-import-expressions

    【讨论】:

      猜你喜欢
      • 2013-07-09
      • 2012-12-18
      • 2013-05-25
      • 2021-11-08
      • 1970-01-01
      • 2010-12-31
      相关资源
      最近更新 更多