如何使用打字稿做出一个shell执行节点的文件 [英] How to make a shell executable node file using TypeScript
问题描述
通常,在节点的文件,我只是把
Normally in node files I just put
#!/usr/bin/env node
在顶部并使其可执行以创建可从一个bash终端中运行的文件。但是,如果我这样做,在一个打字稿文件,编译说:错误TS1001:意外#字符,并拒绝进行编译。那么,如何可以与一个打字稿外壳可执行节点的文件?
at the top and make it executable to create a file that can be run from a bash terminal. However if I do that in a Typescript file, the compiler says "error TS1001: Unexpected character "#"" and refuses to compile it. So how can I make a shell executable node file with Typescript?
推荐答案
您是对报告的bug微软,他们是错的,收为 wontfix 的
You were right to report the bug to Microsoft, and they were wrong to close it as wontfix.
,直到它的是的固定的,这里有一个解决方法。以下内容粘贴到一个文本文件并将其保存为 shebangify
:
Until it is fixed, here's a workaround. Paste the following into a text file and save it as shebangify
:
#!/usr/bin/env node
var fs = require('fs');
var path = process.argv[2];
var data = "#!/usr/bin/env node\n\n";
data += fs.readFileSync(path);
fs.writeFileSync(path, data);
(注意要保留这个答案简洁,code上面没有任何错误检查或其他改进,所以需要您自担风险使用或使用的此内容来代替。另外,看到的这太问题约prepending的文件更多的信息。)
(N.B. To keep this answer concise, the code above doesn't have any error-checking or other refinements, so use at your own risk or use this instead. Also, see this SO question for more info about prepending to files.)
通过使用终端导航到该文件的目录,并执行与制作该文件的可执行文件:
Make the file executable with by using a terminal to navigate to the file's directory and executing:
$ chmod +x shebangify
一旦你创建了一个打字稿程序(例如名为 myscript.ts
),您希望编译,变成一个shell脚本(如名为
Once you have created a Typescript program (e.g. called myscript.ts
) that you wish to compile and turn into a shell script (e.g. called myscript
), do so by executing a sequence along these lines in your terminal:
$ tsc --out myscript myscript.ts ; ./shebangify myscript ; chmod +x myscript
这篇关于如何使用打字稿做出一个shell执行节点的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!