Project Structure, Compilation, and Running TypeScript - Textnotes

Project Structure, Compilation, and Running TypeScript


Learn how to use TypeScript with Node.js for building server-side applications. This module explains project structure, the TypeScript compilation process, and running TypeScript code in a Node.js environment.

1. Project Structure

A typical TypeScript Node.js project includes separate folders for source files and compiled output.

Example Structure


my-node-app/
├─ src/
│ ├─ index.ts
│ ├─ server.ts
│ └─ routes/
│ └─ user.ts
├─ dist/
├─ package.json
├─ tsconfig.json
└─ node_modules/
  1. src/ – contains TypeScript source code
  2. dist/ – compiled JavaScript output
  3. tsconfig.json – TypeScript compiler configuration

Organizing files this way ensures maintainable and scalable applications.

2. Compilation Process

TypeScript code must be compiled into JavaScript before running in Node.js.

Install TypeScript


npm install typescript --save-dev

tsconfig.json Example


{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": ["src"]
}

Compile Command


npx tsc
  1. Converts .ts files in src/ to .js files in dist/
  2. Ensures strict type checking and module resolution

3. Running TypeScript in Node

After compilation, run the JavaScript output with Node.js.

Run Compiled Code


node dist/index.js

Optional: Using ts-node for Development

ts-node allows running TypeScript files directly without pre-compilation.


npm install ts-node --save-dev
npx ts-node src/index.ts

This is useful for development, testing, or scripts without needing tsc.

Conclusion

Using TypeScript with Node.js provides type safety, better maintainability, and scalable server-side development. A clear project structure, proper compilation with tsc, and optional ts-node usage streamline development and reduce runtime errors.