简体   繁体   English

如何通过nodejs使用TypeScript编译器?

[英]How can I use TypeScript compiler through nodejs?

I have a sample code and saved it to a file such as hello.ts我有一个示例代码并将其保存到一个文件中,例如hello.ts

After installing nodejs on windows use below command for installing typescript在 windows 上安装 nodejs 后,使用以下命令安装 typescript

npm install -g typescript

How can I compile hello.ts with node.js directly?如何直接用 node.js 编译hello.ts

When I install "TypeScript 1.6 in VS2015" and use tsc.exe don't have any problem but I want to use node.js instead of VS 2015 extension当我安装“VS2015 中的 TypeScript 1.6”并使用 tsc.exe 时没有任何问题,但我想使用 node.js 而不是 VS 2015 扩展

Please guide me generate.js and.ds through Node.js请通过 Node.js 指导我生成.js 和.ds

Please guide me generate .js and .ds through Node.js 请指导我通过Node.js生成.js和.ds

You have two options: 您有两种选择:

  • Run tsc.js as a node script tsc.js作为节点脚本运行
  • Use typescript as an npm module 使用typescript作为npm模块

Run node tsc.js 运行node tsc.js

This is the approach taken by some tools eg grunt-ts . 这是某些工具(例如grunt-ts You basically just call spawn on the current process process.execPath passing in the other commands as args ( -d ). 基本上,您只需在当前进程process.execPath上调用spawn ,并将其他命令作为args( -d )传入。

One sample 一个样品

Run TypeScript as a node module 将TypeScript作为节点模块运行

If you are playing with the typescript compiler API highly recommend NTypeScript See the Readme for reasons . 如果您正在使用的打字稿编译器API打极力推荐NTypeScript自述原因

The TypeScript compiler provides a simple function called transpile that you can use to get the expected output and then write it out to disk yourself. TypeScript编译器提供了一个称为transpile的简单函数,您可以使用该函数获取预期的输出,然后将其自己写出到磁盘。

PS: I have some docs on the TypeScript compiler internals here : https://basarat.gitbooks.io/typescript/content/docs/compiler/overview.html PS:我在这里有一些关于TypeScript编译器内部的文档: https : //basarat.gitbooks.io/typescript/content/docs/compiler/overview.html

Run tsc in the command line, you'll have the help page. 在命令行中运行tsc ,您将获得帮助页面。 Compiling a script is easy, just tsc hello.ts in the folder containing your script, you'll get a hello.js file. 编译脚本很容易,只要在包含脚本的文件夹中tsc hello.ts ,您就会得到一个hello.js文件。

My preferred way to get going is to use typescript-require . 我最喜欢的方式是使用typescript-require this library basically adds nodejs support for typescript. 这个库基本上增加了nodejs对typescript的支持。

your index file should be a javascript file and it will look like this 您的索引文件应该是一个javascript文件,它看起来像这样

require('typescript-require');
require('./src/main.ts');

and main.ts is a typescript file. main.ts是一个打字稿文件。

Here's a programatically way from TS/Node to run the equivalent of tsc from within a code itself (Note: this uses the TypeScript Compiler API ):这是从 TS/Node 以编程方式从代码本身运行等效于tsc的方法(注意:这使用TypeScript 编译器 API ):

https://gist.github.com/rnag/0d8fe2e72dc7b48743c13f9ca8837a4c https://gist.github.com/rnag/0d8fe2e72dc7b48743c13f9ca8837a4c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM