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 coffee hello.coffee
and ES6 has babel-node hello.js
. How do I do the same with Typescript?
My project has a tsconfig.json
which is used by Webpack/ts-loader to build a nice little bundle for the browser. I have a need for a build step run from the console before that, though, that would use some of the .ts
files used in the project to generate a schema, but I can't seem to be able to run a single Typescript file without compiling the whole project.
This question is related to
node.js
typescript
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.Run the below commands and install the required packages globally:
npm install -g ts-node
npm install -g typescript
Now run the following command to execute a typescript file:
ts-node typescript-file.ts
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.
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")You can use esrun that executes almost instantly a typescript file.
Advantages over 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
There is also an option to run code directly from the CLI, not the *.ts
file itself.
It's perfectly described in the ts-node manual.
ts-node
globally via npm, yarn, or whatever you like.ts-node -e 'console.log("Hello, world!")'
(you may also add the -p
flag for printing code)This little command is perfect for checking, does everything installed fine. And for finding some other error, relevant with tsconfig.json
options.
Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.
#!/usr/bin/env bash
NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc
export TSC="$NODEPATH/tsc"
export NODE="$NODEPATH/node"
TSCFILE=$1 # only parameter is the name of the ts file you created.
function show_usage() {
echo "ts2node [ts file]"
exit 0
}
if [ "$TSCFILE" == "" ]
then
show_usage;
fi
JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"
$TSC $TSCFILE && $NODE $JSFILE
You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:
# tsrun myscript.ts
Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.
This answer may be premature, but deno supports running both TS and JS out of the box.
Based on your development environment, moving to Deno (and learning about it) might be too much, but hopefully this answer helps someone in the future.
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.
Write yourself a simple bash wrapper may helps.
#!/bin/bash
npx tsc $1 && node ${1%%.ts}
This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts
will also run.
None of the other answers discuss how to run a TypeScript script that uses modules, and especially modern ES Modules.
First off, ts-node doesn't work in that scenario, as of March 2020. So we'll settle for tsc
followed by node
.
Second, TypeScript still can't output .mjs
files. So we'll settle for .js
files and "type": "module"
in package.json
.
Third, you want clean import
lines, without specifying the .js
extension (which would be confusing in .ts
files):
import { Lib } from './Lib';
Well, that's non-trivial. Node requires specifying extensions on imports, unless you use the experimental-specifier-resolution=node
flag. In this case, it would enable Node to look for Lib.js
or Lib/index.js
when you only specify ./Lib
on the import
line.
Fourth, there's still a snag: if you have a different main
filename than index.js
in your package, Node won't find it.
Transpiling makes things a lot messier than running vanilla Node.
Here's a sample repo with a modern TypeScript project structure, generating ES Module code.
We have following steps:
First you need to install typescript
npm install -g typescript
Create one file helloworld.ts
function hello(person){
return "Hello, " + person;
}
let user = "Aamod Tiwari";
const result = hello(user);
console.log("Result", result)
Open command prompt and type the following command
tsc helloworld.ts
Again run the command
node helloworld.js
Result will display on console
Source: Stackoverflow.com