Gunchars
Gunchars

Reputation: 10996

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.

Upvotes: 807

Views: 1159504

Answers (27)

Amr Salem
Amr Salem

Reputation: 267

Now with node version 23.6.0 you can simply execute the ts file directly

node file.ts :D

enter image description here

Upvotes: 2

basarat
basarat

Reputation: 276161

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.

To run a single TypeScript file without compiling the whole project, there is ts-node that will compile the code on the fly and run it through Node:

npx ts-node src/foo.ts

Upvotes: 1054

João Lenon
João Lenon

Reputation: 325

Since V22.6.0, Node.js has experimental support for some TypeScript syntax!!

You can write code that's valid TypeScript directly in Node.js without the need to compile it:

node --experimental-strip-types example.ts

Keep in mind that this will never validate your types, instead, your types are just being cut off from your file so Node.js is able to run it as JavaScript. You will still need other libraries such as tsc if you want to validate your types.

Upvotes: 0

KeyKi
KeyKi

Reputation: 3213

npx tsx ./demo.ts

It has the notable start delay. For me, it's 1600 ms.

However, if you will use tsx the follow way:

node --require ./node_modules/tsx/dist/loader.cjs ./demo.ts

(or node --import ./node_modules/tsx/dist/loader.mjs ./demo.ts)

With this command the start delay will be less than twice. Only 700 ms.

In my case I use the relative path to loader.cjs, since tsx is installed as a project's dev dependency.

Here is how package.json looks:

{
  "scripts": {
    "demo": "node --require ./node_modules/tsx/dist/loader.cjs ./demo.ts",
    "demo-slow": "npx tsx ./demo.ts"
  },
  "devDependencies": {
    "tsx": "4.19.1"
  }
}

Upvotes: 0

BananaAcid
BananaAcid

Reputation: 3471

I am using npx tsx index.ts or more precisely npx --yes tsx --watch index.ts from package.scripts.dev

bun did not have all the modules I needed (namely statfs)

Upvotes: 0

Ugwu Somto
Ugwu Somto

Reputation: 440

You can use ts-node as it allows you run typescript without compiling it

install it and typescript

npm install -D ts-node typescript

then create tsconfig.json in your root and add the configurations

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

Then you can run your file

npx ts-node src/index.ts

Upvotes: 0

sckdd
sckdd

Reputation: 79

FYI: node.js added support for .ts files by using the flag --experimental-strip-types:

node file.ts --experimental-strip-types

Upvotes: 7

A.A.
A.A.

Reputation: 251

I tried the following as a workaround to run ts files from command line

tsc --watch // compile, generate js files and watch for any later changes
node index.js // you can replace node with nodemon as well to automatically restart your app

Upvotes: 0

Muhammad Ali Nazar
Muhammad Ali Nazar

Reputation: 1839

You can also try tsx. tsx is a CLI command (alternative to node) for seamlessly running TypeScript, it's built upon esbuild so it's very fast.

https://github.com/esbuild-kit/tsx

Example:

npx tsx ./script.ts

Upvotes: 136

Xuan
Xuan

Reputation: 5629

Use bun.

It's faster and has a lot of tooling bundled in.

bun run ./my-script.ts

Upvotes: 17

Gin Quin
Gin Quin

Reputation: 1113

I created @digitak/esrun, a thin wrapper around esbuild and that executes a TypeScript file almost instantly. esrun was made because I was disappointed with ts-node: too slow, and just didn't work most of the time.

Advantages of esrun over ts-node include:

  • very fast (uses esbuild),
  • can import ESM as well as CJS (just use the libraries of your choice and esrun 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 esrun in inspect mode to use the DevTools console instead of your terminal console.

After installing, just run:

npx @digitak/esrun file.ts

Upvotes: 55

M Omer Sharif Bhatti
M Omer Sharif Bhatti

Reputation: 132

Here is the command

tsc index.ts --outDir .temp && node .temp/index.js && rm -rf .temp
<<<<<<<<< Compile >>>>>>>>> <<<<<<< Run >>>>>>> << Clean >>

Upvotes: 7

Vasilis Plavos
Vasilis Plavos

Reputation: 583

  1. Create your TypeScript file (ex. app.ts)
  2. npm i -D typescript ts-node -> to install the dev dependencies local
  3. npx nodemon app.ts

Using nodemon, automatically recompile app.ts every time you change the file

Upvotes: 4

Deepak Yadav
Deepak Yadav

Reputation: 1772

We can run it using nodemon as well

nodemon ./filepath/filename.ts

Upvotes: -3

Dan Dascalescu
Dan Dascalescu

Reputation: 151906

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.

Upvotes: 49

bcbrian
bcbrian

Reputation: 327

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

Upvotes: 16

robd
robd

Reputation: 9825

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.

Upvotes: 12

Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 5634

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

Upvotes: 235

tony2tones
tony2tones

Reputation: 1670

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

Upvotes: 57

AlexZeDim
AlexZeDim

Reputation: 4342

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.

Upvotes: 0

Aamod Tiwari
Aamod Tiwari

Reputation: 1466

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

Upvotes: 126

Daniel T
Daniel T

Reputation: 1169

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

Upvotes: 7

Paramvir Singh Karwal
Paramvir Singh Karwal

Reputation: 616

  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.

Upvotes: 1

Kariem
Kariem

Reputation: 4873

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.

Upvotes: 7

Joyer
Joyer

Reputation: 431

Write yourself a simple bash wrapper may helps.

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

Upvotes: 9

Alexander Emelianov
Alexander Emelianov

Reputation: 588

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.

Upvotes: 20

Harlin
Harlin

Reputation: 1139

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.

Upvotes: 4

Related Questions