
Node.js Setup with TypeScript
Setting up a Node.js project with TypeScript is straightforward and brings type safety to your backend development. This guide walks you through the process, inspired by Oka's style.
Watch the Tutorial
1. Initialize Your Project
mkdir my-node-ts-app
cd my-node-ts-app
npm init -y
2. Install Dependencies
Install TypeScript and essential types:
npm install --save-dev typescript @types/node ts-node nodemon
3. Create a TypeScript Configuration
Generate a tsconfig.json
file:
tsconfig.json
1{
2 "compilerOptions": {
3 "target": "ES2020",
4 "module": "commonjs",
5 "outDir": "dist",
6 "rootDir": "src",
7 "strict": true,
8 "esModuleInterop": true
9 }
10}
4. Project Structure
Project Structure
1my-node-ts-app/
2├── src/
3│ └── index.ts
4├── package.json
5├── tsconfig.json
5. Sample Express Server
Install Express and its types:
npm install express
npm install --save-dev @types/express
Create src/index.ts
:
src/index.ts
1import express from 'express';
2
3const app = express();
4const port = 3000;
5
6app.get('/', (req, res) => {
7res.send('Hello, TypeScript with Node.js!');
8});
9
10app.listen(port, () => {
11console.log("Server running at http://localhost:port");
12});
6. Add Scripts to package.json
package.json
1"scripts": {
2 "dev": "nodemon src/index.ts",
3 "build": "tsc",
4 "start": "node dist/index.js"
5}
7. Run Your Project
For development:
npm run dev
To build and start:
npm run build
npm start