How to make a shell executable node file using TypeScript How to make a shell executable node file using TypeScript bash bash

How to make a shell executable node file using TypeScript


See https://github.com/Microsoft/TypeScript/blob/master/bin/tsc for an example. Basically have a dummy file without the .js extension and just require the actual .js file.

E.g. In file named tsc:

#!/usr/bin/env noderequire('./tsc.js')


You were right to report the bug to Microsoft, and they were wrong to close it as wontfix.

Until it is fixed, here's a workaround. Paste the following into a text file and save it as shebangify:

#!/usr/bin/env nodevar fs = require('fs');var path = process.argv[2];var data = "#!/usr/bin/env node\n\n";data += fs.readFileSync(path);fs.writeFileSync(path, data);

(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

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


I don't have enough reputation points to post a comment, but I'd just thought it'd be good for everyone to know that I opened a new issue on GitHub since that's what the Typescript devs are using to track things like this: https://github.com/Microsoft/TypeScript/issues/2749 .