Last updated: Feb 27, 2024
Reading time·3 min
Use the ts-node
package to run a TypeScript file from the command line, e.g.
npx ts-node myDirectory/myFile.ts
.
The ts-node
command will transpile the TypeScript file to JavaScript and
will run the code in a single step.
Here is the TypeScript file we will run from the command line.
function sum(a: number, b: number) { console.log(`The result is: ${a + b}`); return a + b; } sum(20, 30); // 👉️ 50
The file is located at src/index.ts
and I have opened my terminal in the
directory that contains the src
directory.
To run the TypeScript file, we have to use the ts-node package.
Open your terminal in a directory from which you want to run the file and specify the correct path to the file.
npx ts-node src/index.ts
If you haven't installed TypeScript on your machine, you can do so by running the following command.
npm install -g typescript # Depending on your configuration, you may also need the typings npm install -D tslib @types/node
If you get an error about not having sufficient permissions when installing
TypeScript globally, prefix the command with sudo
(macOS or Linux), or open
CMD as an administrator (Windows).
sudo npm install -g typescript
The npx ts-node myFile.ts
command transpiles the TypeScript code to JavaScript
and runs the code with Node.js.
npx ts-node src/index.ts
You could manually do this by running the
tsc (TypeScript compiler) and node
commands yourself.
tsc src/index.ts node src/index.js
The tsc myFile.ts
command will generate a .js
file with the same name in the
same directory.
Here is the src/index.js
file that was generated.
function sum(a, b) { console.log('The result is: '.concat(a + b)); return a + b; } sum(20, 30); // 👉️ 50
Now we can run the file with node
.
node src/index.js
This is exactly what ts-node
does under the hood, but it does it without
generating a JavaScript file.
If you have a TypeScript project with a
tsconfig.json file, you can open your
terminal in the root directory (the one with tsconfig.json
) and start tsc
in
watch mode.
tsc --watch -p . # or with npx npx tsc --watch -p .
Where the generated JavaScript files will be placed depends on the outDir
option in your tsconfig.json
file.
outDir
set to a directory named build
, the TypeScript compiler will watch for changes in your project, transpile your .ts
files to .js
files and add the .js
files to your build
directory.You can run any .js
file with node myFile.js
and any TypeScript file with
npx ts-node myFile.ts
.
Notice that we use npx
when running the ts-node
command.
npx
basically checks if a package (ts-node
in this case) is installed
locally (in package.json
) or installed globally and runs it.
If the package is not installed, npx
downloads and runs the package.
If you get the error tsc command not found, click on the link and follow the instructions.
You can learn more about the related topics by checking out the following tutorials: