I\'m having a surprisingly hard time finding an answer to this. With plain Node.JS, you can run any js file with node path/to/file.js
, with CoffeeScript it\'s <
Like Zeeshan Ahmad's answer, I also think ts-node
is the way to go. I would also add a shebang and make it executable, so you can just run it directly.
Install typescript and ts-node globally:
npm install -g ts-node typescript
or
yarn global add ts-node typescript
Create a file hello
with this content:
#!/usr/bin/env ts-node-script
import * as os from 'os'
function hello(name: string) {
return 'Hello, ' + name
}
const user = os.userInfo().username
console.log(`Result: ${hello(user)}`)
As you can see, line one has the shebang for ts-node
Run directly by just executing the file
$ ./hello
Result: Hello, root
Some notes:
Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script
instead of ts-node
, link to issues in ts-node.
To add to @Aamod answer above, If you want to use one command line to compile and run your code, you can use the following:
Windows:
tsc main.ts | node main.js
Linux / macOS:
tsc main.ts && node main.js
This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts
will also run.
For environments such as Webstorm where the node
command cannot be changed to ts-node
or npx
:
npm install ts-node typescript
(Install dependencies)node --require ts-node/register src/foo.ts
(Add --require ts-node/register
to "Node parameters")Just helpful information - here is newest TypeScript / JavaScript runtime Deno.
It was created by the creator of node Ryan Dahl, based on what he would do differently if he could start fresh.
ts-node
node module globally.node
in command line to run below file js
file (The path is for windows, but you can do it for linux as well)
~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
ts
file path as a command line argument.