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.
How do I do the same with Typescript
You can leave tsc
running in watch mode using tsc -w -p .
and it will generate .js
files for you in a live fashion, so you can run node foo.js
like normal
TS Node
There is ts-node : https://github.com/TypeStrong/ts-node that will compile the code on the fly and run it through node 🌹
npx ts-node src/foo.ts
Run the below commands and install the required packages globally:
npm install -g ts-node typescript '@types/node'
Now run the following command to execute a typescript file:
ts-node typescript-file.ts
ts-node
also provides TypeScript REPL.
npx ts-node yourscript.ts
in case you don't want to use global version.
npm install typescript --save-dev --global && npm i ts-node -g
instead
'@types/node'
I recommend taking a look at these links: npmjs.com/package/@types/node , alura.com.br/artigos/… [🇧🇷], blog.angular-university.io/… . 😊
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
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
npm install typescript -g
to install tsc
CLI
Edit: May 2022
ts-node
now has an --esm
flag use it.
Old Answer:
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.
--esm
flag. You answer is my fav! Could you update to help future devs :)
You can use the @digitak/esrun library, which is a thin wrapper around esbuild and that executes almost instantly a typescript file.
I am the author of the library.
I created it because I was disappointed with ts-node
: too slow, and it just don't work most of the times.
Advantages of esrun over ts-node
:
very fast (use esbuild),
can import ESM as well as CJS (just use the libraries of your choice and it will work out of the box),
there is an included watch mode, run your script with the "--watch" option and any change to your entry file or any of its dependencies will re-trigger the result,
you can use it in inspect mode to use the DevTools console instead of your terminal console.
ts-node
to work. Simply ran "esrun my-file.ts", and worked out of the box !
ts-node
was troubles and slowness and I wanted to have a modern typescript runner. I also consider it's not really my work since I've only written a small wrapper around the awesome EsBuild library from Evan W - he is the guy who deserves all the credits.
npx @digitak/esrun index.ts
replacing index.ts
if required.
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.
deno run https://deno.land/std/examples/welcome.ts
Deno is secure by default. Therefore, unless you specifically enable it, a deno module has no file, network, or environment access for example.
add the extra flags while developing. then lock it down: deno run --unstable --allow-read --allow-env main.ts
-> dev.to/mxfellner/…
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:
This does not seem to work with ES modules, as Dan Dascalescu has pointed out.
See this issue discussing the best way to make a command line script with package linking, provided by Kaspar Etter. I have improved the shebang accordingly
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.
#!/usr/bin/env ts-node-script
(also part of ts-node
) seems to be superior for this purpose. If you want to link your script (e.g. with npm link
), things get more complicated as the script mode of ts-node
does not (yet?) follow symbolic links. I went with #!/usr/bin/env -S ts-node --project /usr/local/lib/node_modules/<your-project>/tsconfig.json
in the end in my case.
For linux / mac you can add the ts-node-script
shebang.
Install typescript / ts-node globally (see 1 below for non global install):
npm install ts-node typescript --save-dev --global
Add this as the first line in your .ts
file:
#!/usr/bin/env ts-node-script
Then make the file executable:
$ chmod +x ./your-file.ts
You can then run the file directly from the command line:
$ ./your-file.ts
Notes:
1 For non global install you can install local to your project
npm install ts-node typescript --save-dev
and add the relative path to the shebang script eg:
#!/usr/bin/env ./node_modules/.bin/ts-node-script
2 Support for shebangs was officially added in ts-node v8.9.0.
Write yourself a simple bash wrapper may helps.
#!/bin/bash
npx tsc $1 && node ${1%%.ts}
As of May 2022 ts-node
does support es modules
npx ts-node --esm file.ts
you will likely need to add "type": "module",
to your package.json
. And some of the imports might be wonky unless you turn on experimental-specifier-resolution=node
npmjs.com/package/ts-node#commonjs-vs-native-ecmascript-modules
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")
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 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.
Install ts-node node module globally. Create node runtime configuration (for IDE) or use 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 Give your ts file path as a command line argument. Run Or Debug as you like.
in my mac m1 I had to escape the .(period)
ts-node index\ ts
ofcourse along with npm i -g typescript ts-node @types/node
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.
As a first step, install ts-node globally via npm, yarn, or whatever you like. ...and now just use 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.
This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts
will also run.
Success story sharing
npm install -g ts-node
makests-node your-script.ts
a breeze.deno run path/to/file.ts
and it will run typescript files in a single command without compiling it to a separate JS file.