从内存中的字符串加载TypeScript模块?

时间:2018-11-23 04:56:40

标签: node.js typescript

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}
`));

我们可以要求节点模块。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)