Normally in node files I just put
#!/usr/bin/env node
at the top and make it executable to create a file that can be run from a bash terminal.
I've never been able to get ts-node
to work, so I finally made my own way to write shell scripts in TypeScript. If there were a package manager for Bash I would make a package, but there isn't, so I just put this script in my path as ts-exec
:
#!/usr/bin/env bash
file_to_run="$1"
basename=`basename "$1"`
tmp_prefix=`basename "$BASH_SOURCE"`
TMPDIR=`mktemp -d -t "$tmp_prefix-XXXXXXXXXX"`
pushd "$TMPDIR" > /dev/null
cp "$1" "$basename.ts"
tsc "$basename"
node "$basename.js"
popd > /dev/null
rm -rf "$TMPDIR"
And now I can do things like this:
#!/usr/bin/env ts-exec
let greeting: string = "Hello World!";
console.log( greeting );
And it works.
Of course, it does have some limitations
... so basically it's for bash nerds who want to use TypeScript for small scripts that would be a pain to write as Bash scripts. I'm still baffled that ts-node
doesn't cover this case, and I'd rather not have to futz with temp files that might get left behind and waste space if there's an error, but so far this covers my use-case. (Besides, I've got that cronjob that deletes everything in ~/tmp
that's more than 31622400 seconds old every night, so stray temp files can't eat my whole system.)