Question
I want to run a TypeScript file from the command line in a way similar to how JavaScript can be run with node path/to/file.js, CoffeeScript with coffee hello.coffee, or transpiled ES6 with babel-node hello.js.
My project already has a tsconfig.json file that is used by Webpack and ts-loader to build a browser bundle. However, I also need a separate build step that runs from the console before bundling. That step should use some existing .ts files in the project to generate a schema.
What is the correct way to run a single TypeScript file from the command line without compiling the entire project first?
Short Answer
By the end of this page, you will understand the main ways to run TypeScript from the command line, when to compile first versus run directly, and which tools are commonly used in real projects. You will also see how tsconfig.json affects command-line execution and how to run a single script for build or automation tasks.
Concept
TypeScript is not executed directly by Node.js in the same way as plain JavaScript. Node runs JavaScript, but TypeScript adds syntax such as type annotations, interfaces, and other features that must usually be transformed before execution.
There are two common approaches:
- Compile first, then run
- Use the TypeScript compiler (
tsc) to convert.tsfiles into.js - Then run the generated JavaScript with Node.js
- Use the TypeScript compiler (
- Run TypeScript directly with a runtime tool
- Use a tool such as
ts-nodethat compiles TypeScript just in time and executes it immediately
- Use a tool such as
This matters because many real projects use TypeScript not only for web apps, but also for:
- build scripts n- code generation
- database migrations
- CLI tools
- test setup scripts
If you only need a quick command-line script, running TypeScript directly is often the easiest developer experience. If you need maximum control or production-ready output, compiling first is usually the safer choice.
Mental Model
Think of TypeScript as a recipe written in a slightly richer language than the kitchen understands.
- Node.js is the kitchen: it only understands JavaScript
- TypeScript is the recipe with extra notes and labels
tscis a translator that rewrites the recipe into plain JavaScript before the kitchen uses itts-nodeis a live interpreter that translates the recipe on the spot while the kitchen is working
So when you ask to “run a TypeScript file,” what you are really asking is either:
- “Translate it first, then run it”
- or “Use a tool that translates and runs it in one step”
Syntax and Examples
Option 1: Compile with tsc, then run with Node
Install TypeScript if needed:
npm install --save-dev typescript
Compile a file:
npx tsc src/generate-schema.ts
Run the output:
node src/generate-schema.js
If your tsconfig.json outputs files into a folder such as dist, then run the compiled file from there:
npx tsc
node dist/generate-schema.js
Option 2: Run directly with ts-node
Install ts-node:
npm install --save-dev ts-node typescript
Run a TypeScript file directly:
npx ts-node src/generate-schema.ts
This is the closest equivalent to commands like:
node file.js
coffee file.coffee
babel-node file.js
Example TypeScript file
function buildMessage(name: string): string {
return `Generating schema for ${name}`;
}
console.log(buildMessage("users"));
Run it with ts-node:
npx ts-node script.ts
Output:
Generating schema for users
Using npm scripts
A common pattern is to add a script to package.json:
{
"scripts": {
"generate-schema": "ts-node src/generate-schema.ts"
}
}
Then run:
npm run generate-schema
This keeps your command easy to remember and consistent across team members.
Step by Step Execution
Consider this file:
const inputFile: string = "models.ts";
const outputFile: string = "schema.json";
console.log("Starting...");
console.log(`Reading ${inputFile}`);
console.log(`Writing ${outputFile}`);
console.log("Done.");
If you run it with:
npx ts-node generate-schema.ts
Here is what happens step by step:
ts-nodereadsgenerate-schema.ts- It uses the TypeScript compiler settings, usually from
tsconfig.json - TypeScript syntax such as
: stringis transformed into plain JavaScript - The resulting JavaScript is executed by Node.js
- The console output appears in this order:
Starting...
Reading models.ts
Writing schema.json
Done.
If you use tsc instead:
npx tsc generate-schema.ts
node generate-schema.js
The process changes slightly:
tsccompiles the file and createsgenerate-schema.js- Node.js runs that JavaScript file
- The output is the same, but compilation and execution are separate steps
Real World Use Cases
Running TypeScript files from the command line is very common outside the main application runtime.
Common use cases
- Schema generation
- Read TypeScript models and generate JSON schema or API definitions
- Database migrations
- Run scripts that create or update tables
- Seed scripts
- Insert initial data into a database
- Build helpers
- Generate config files, localization files, or metadata before bundling
- Developer tooling
- Lint setup scripts, release scripts, changelog generation
- Data processing
- Transform CSV, JSON, or log files with typed code
Example scenario
A project may have shared TypeScript types like this:
export interface User {
id: number;
name: string;
email: string;
}
A command-line script can import that type-related module or related metadata and generate files used elsewhere in the build process. This avoids duplicating logic in a separate scripting language.
Real Codebase Usage
In real projects, developers usually do not type long commands manually every time. Instead, they use repeatable patterns.
Typical patterns
npm scripts
{
"scripts": {
"build": "webpack",
"generate:schema": "ts-node scripts/generate-schema.ts",
"seed": "ts-node scripts/seed.ts"
}
}
This makes build steps easy to run in CI and on other machines.
Separate scripts folder
Many codebases place command-line TypeScript files in a dedicated folder:
project/
src/
scripts/
generate-schema.ts
seed.ts
tsconfig.json
Validation and guard clauses
Command-line scripts often validate inputs early:
const target = process.argv[2];
if (!target) {
console.error("Please provide a target name.");
process.exit(1);
}
This is a common guard clause pattern.
Error handling
Real scripts usually fail clearly when something goes wrong:
async function main() {
throw new Error("Something went wrong");
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
Shared configuration
Projects often use one tsconfig.json for app code and another for scripts, especially if browser code and Node scripts need different settings.
For example:
tsconfig.jsonfor the main apptsconfig.scripts.jsonfor command-line tools
This helps avoid conflicts between browser-focused and Node-focused compiler options.
Common Mistakes
1. Expecting Node.js to run .ts files directly
Broken example:
node script.ts
Why it fails:
- Node does not understand TypeScript syntax by default
Fix:
npx ts-node script.ts
or:
npx tsc script.ts
node script.js
2. Compiling the entire project when only one script is needed
Beginners often run:
npx tsc
This may compile every included file in the project.
If you only want one file, use:
npx tsc path/to/script.ts
Or use ts-node to avoid the separate compile step.
3. Forgetting that tsconfig.json can affect the script
A browser-focused tsconfig.json may not work well for Node-based scripts.
For example, a script that uses process.argv may need Node typings.
Fix:
npm install --save-dev @types/node
And make sure your config supports Node usage.
4. Using imports that do not match your module setup
Broken example:
import fs from "fs";
Depending on your config, this may fail.
Safer version in many setups:
import * as fs from "fs";
The correct import style depends on your TypeScript module settings.
5. Ignoring output location when compiling
You may compile a file and then try to run the wrong path.
Broken flow:
npx tsc src/script.ts
node dist/script.js
If tsc emitted the file elsewhere, that path will fail.
Always confirm where the compiled .js file was created.
6. Not handling async errors
Broken example:
async function main() {
await Promise.reject(new Error("Failed"));
}
main();
Better:
main().catch((error) => {
console.error(error);
process.exit(1);
});
Comparisons
| Approach | How it works | Best for | Pros | Cons |
|---|---|---|---|---|
node file.js | Runs JavaScript directly | Plain JavaScript files | Fast and simple | Cannot run TypeScript syntax |
tsc then node | Compile TypeScript to JavaScript, then execute | Production scripts, explicit build steps | Clear separation, predictable output | Two-step workflow |
ts-node file.ts | Compiles and runs TypeScript on the fly | Development scripts, tooling, quick automation | Convenient, minimal setup | Slightly slower, depends on runtime tooling |
tsc vs ts-node
| Tool | Main role | Use it when |
|---|---|---|
tsc | Compiler | You want generated JavaScript files |
ts-node | Runtime helper | You want to execute .ts files directly |
One project config vs separate config
| Setup | When it helps |
|---|---|
Single tsconfig.json | Small projects with similar browser and script needs |
| Separate script config | Projects where browser bundling and Node scripts need different options |
Cheat Sheet
# Install tools
npm install --save-dev typescript ts-node
# Compile one file
npx tsc script.ts
# Run compiled JavaScript
node script.js
# Run TypeScript directly
npx ts-node script.ts
Key rules
- Node.js runs JavaScript, not raw TypeScript
- TypeScript must be compiled first or handled by a runtime tool like
ts-node tsconfig.jsonaffects how TypeScript is compiled or executed- Use npm scripts for repeatable commands
Common commands
npx tsc
npx tsc path/to/file.ts
npx ts-node path/to/file.ts
npm run my-script
Good defaults
- Use
ts-nodefor development scripts and internal tooling - Use
tsc+nodewhen you want explicit build output - Install
@types/nodefor Node-based TypeScript scripts
Watch out for
- Running
node file.ts - Wrong output path after compilation
- Browser-focused
tsconfig.jsonsettings used for Node scripts - Missing error handling in async scripts
FAQ
Can Node.js run TypeScript files directly?
No. Node.js runs JavaScript. To run TypeScript, you usually compile it first with tsc or use a tool like ts-node.
What is the easiest way to run a single TypeScript file?
For development or build scripts, npx ts-node file.ts is usually the easiest option.
Do I need to compile the entire project to run one TypeScript file?
No. You can compile a single file with npx tsc path/to/file.ts or run it directly with npx ts-node path/to/file.ts.
Why does my TypeScript script fail even though my app builds with Webpack?
Webpack and ts-loader handle browser bundling, but command-line scripts run in a Node environment. Your TypeScript configuration may need Node-specific settings or typings.
Should I use ts-node in production?
For small internal tooling it can be fine, but many teams prefer compiling with tsc first for production workflows.
Do I need @types/node for command-line scripts?
Usually yes, especially if your script uses process, fs, path, or other Node APIs.
Can I use a separate tsconfig for scripts?
Yes. This is common when app code and command-line scripts have different runtime needs.
Mini Project
Description
Create a small TypeScript command-line script that generates a simple schema file from a list of field names. This demonstrates how to run a .ts file from the console, read command-line arguments, and write output using Node.js APIs.
Goal
Build and run a TypeScript script that accepts field names from the command line and writes a schema.json file.
Requirements
- Create a TypeScript file named
generate-schema.ts. - Read field names from command-line arguments.
- Build a JSON object where each field maps to the string
"string". - Write the result to a file named
schema.json. - Print a success message when the file is created.
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Accessing Input Value from EventTarget in TypeScript
Learn why EventTarget has no value property in TypeScript and safely read values from HTML input events in Angular applications.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.