How to run TypeScript files from command line?

node.jsTypescript

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

> 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

Solution 2 - node.js

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

Solution 3 - node.js

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

Solution 4 - node.js

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

Solution 5 - node.js

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.

Solution 6 - node.js

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.

Solution 7 - node.js

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.

Solution 8 - node.js

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.

Solution 9 - node.js

Write yourself a simple bash wrapper may helps.

#!/bin/bash
npx tsc $1 && node ${1%%.ts}

Solution 10 - node.js

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.

Solution 11 - node.js

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.

Solution 12 - node.js

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.

Solution 13 - node.js

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")

Solution 14 - node.js

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

Solution 15 - node.js

  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.

Solution 16 - node.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.

Solution 17 - node.js

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

Solution 18 - node.js

This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts will also run.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuncharsView Question on Stackoverflow
Solution 1 - node.jsbasaratView Answer on Stackoverflow
Solution 2 - node.jsziishanedView Answer on Stackoverflow
Solution 3 - node.jsAamod TiwariView Answer on Stackoverflow
Solution 4 - node.jstony2tonesView Answer on Stackoverflow
Solution 5 - node.jsDan DascalescuView Answer on Stackoverflow
Solution 6 - node.jsAlexander EmelianovView Answer on Stackoverflow
Solution 7 - node.jsGin QuinView Answer on Stackoverflow
Solution 8 - node.jsKariemView Answer on Stackoverflow
Solution 9 - node.jsJoyerView Answer on Stackoverflow
Solution 10 - node.jsrobdView Answer on Stackoverflow
Solution 11 - node.jsvaragrawalView Answer on Stackoverflow
Solution 12 - node.jsHarlinView Answer on Stackoverflow
Solution 13 - node.jsDaniel TView Answer on Stackoverflow
Solution 14 - node.jsbcbrianView Answer on Stackoverflow
Solution 15 - node.jsParamvir Singh KarwalView Answer on Stackoverflow
Solution 16 - node.jsAlexZeDimView Answer on Stackoverflow
Solution 17 - node.jsMehul PamaleView Answer on Stackoverflow
Solution 18 - node.jseven2468View Answer on Stackoverflow