Setting up a TypeScript Project with Node.js
This guide walks you through setting up a production-ready TypeScript environment for Node.js from scratch.
1. Initialize the Project
Create a folder and initialize a standard Node.js project.
mkdir my-ts-app
cd my-ts-app
npm init -y
2. Install Dependencies
You need the TypeScript compiler and the type definitions for Node.js (so TypeScript understands globals like process, console, and modules like fs).
npm install typescript @types/node --save-dev
3. Initialize TypeScript Configuration
Generate a tsconfig.json file.
npx tsc --init
Open tsconfig.json and adjust these settings for a standard Node.js setup:
{
"compilerOptions": {
"target": "es2020", /* Modern Node versions support ES2020+ */
"module": "commonjs", /* Standard for Node.js */
"rootDir": "./src", /* Where your .ts files live */
"outDir": "./dist", /* Where compiled .js files go */
"strict": true, /* Enable strict type-checking */
"esModuleInterop": true, /* Allow default imports from CommonJS modules */
"skipLibCheck": true /* Skip type checking of declaration files */
},
"include": ["src/**/*"]
}
4. Create Source Code
Create a src directory and your entry file.
mkdir src
src/index.ts
const greet = (name: string) => {
console.log(`Hello, ${name}!`);
};
greet("World");
5. Build and Run
To compile your code to JavaScript:
npx tsc
This creates a dist folder containing index.js. Run it with Node:
node dist/index.js
6. Development Workflow (ts-node)
For development, it is tedious to compile manually every time. Use ts-node to run TypeScript files directly in memory.
npm install ts-node --save-dev
npx ts-node src/index.ts
programming/javascript/typescript/typescript programming/javascript/typescript/tsconfig