[node.js] How to run TypeScript files from command line?

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

The answer is


  1. Install ts-node node module globally.
  2. 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
  3. Give your ts file path as a command line argument.
  4. Run Or Debug as you like.

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.

  1. Install typescript and ts-node globally:

    npm install -g ts-node typescript
    

    or

    yarn global add ts-node typescript
    
  2. 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

  3. 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:

  1. npm install ts-node typescript (Install dependencies)
  2. 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:

  • very fast (use esbuild),
  • you can use ES modules without having to add "types": "module" to your package.json,
  • you can also use it as a replacement to Node to execute modern Javascript with ES modules, decorators, class fields, etc...

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.

  1. As a first step, install ts-node globally via npm, yarn, or whatever you like.
  2. ...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.


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:

  1. First you need to install typescript

    npm install -g typescript
    
  2. Create one file helloworld.ts

    function hello(person){
       return "Hello, " + person;
    }
    let user = "Aamod Tiwari";
    const result = hello(user);
    console.log("Result", result)
    
  3. Open command prompt and type the following command

    tsc helloworld.ts
    
  4. Again run the command

    node helloworld.js
    
  5. Result will display on console


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?