Running TypeScript Files from the Command Line

As a developer working with TypeScript, it’s often necessary to run your code directly from the command line. This can be useful for testing, debugging, or executing scripts that don’t require a full build process. In this tutorial, we’ll explore the different ways you can run TypeScript files from the command line.

Installing Dependencies

Before you start running TypeScript files, make sure you have the necessary dependencies installed. You’ll need to install typescript and ts-node (or an alternative like tsx) using npm:

npm install -g typescript ts-node @types/node

Alternatively, if you prefer to use tsx, you can install it separately:

npm install -g tsx

Compiling TypeScript Files

To compile a TypeScript file, you can use the tsc command. For example, to compile a file called hello.ts, run:

tsc hello.ts

This will generate a corresponding JavaScript file called hello.js. You can then run this file using Node.js:

node hello.js

Running TypeScript Files Directly

Instead of compiling your TypeScript files manually, you can use tools like ts-node or tsx to compile and run them directly. Here are some examples:

Using ts-node:

npx ts-node src/hello.ts

This will compile the hello.ts file on the fly and execute it using Node.js.

Using tsx:

npx tsx ./script.ts

Similar to ts-node, tsx compiles your TypeScript code and executes it directly.

Running Multiple Commands

If you want to compile and run your code in one step, you can use the following command:

tsc main.ts && node main.js

On Windows, use the pipe operator (|) instead of &&:

tsc main.ts | node main.js

Note that this approach requires your TypeScript file to be compiled first, and then the resulting JavaScript file is executed.

Conclusion

Running TypeScript files from the command line is a straightforward process once you have the necessary dependencies installed. You can choose between compiling your code manually using tsc or using tools like ts-node or tsx to compile and run it directly. Whether you’re testing, debugging, or executing scripts, being able to run TypeScript files from the command line is an essential skill for any developer working with this popular language.

Leave a Reply

Your email address will not be published. Required fields are marked *