-
Installing basic repositories
mkdir my-express-ts-app && cd my-express-ts-app npm init -y npm install express npm install typescript ts-node @types/node @types/express --save-dev npm install nodemon --save-dev
NOTE:
nodemon
simplifies the development by restarting dev server (to apply changes) on any code modification (= there is no need to restart dev server). Project's configuration
Typescript uses following files structure:
my-express-ts-app ├── node_modules ├── src │ └── index.ts ├── package.json ├── tsconfig.json └── .gitignore
- Create
tsconfig.json
file with following content:{ "compilerOptions": { "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "./dist" }, "include": ["src/**/*"], "exclude": ["node_modules"] }
- Create
.gitignore
file with following content:node_modules dist
Note:
dist
directory is dedicated for compiled javascript files. It will be created with a first compilation. - Modify
scripts
atpackage.json
to the following:"scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "npx nodemon --watch src --exec \"npx ts-node src/index.ts\"" },
devDependencies
should look as follow:"devDependencies": { "@types/express": "^4.17.21", "@types/node": "^20.14.10", "nodemon":"^3.1.4", "ts-node": "^10.9.2", "typescript": "^5.5.3" }
- Create
Writing a sample application
Create
src/index.tx
file and copy following code into it:import express, { Request, Response } from 'express'; const app = express(); const port = 3000; app.get('/', (req: Request, res: Response) => { res.send('Hello World, This is TypeScript sample with Express!'); }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
Running the application for development
npm run dev
Compiling the application for production
npm run build npm start
Introduction to Typescript with Express.js
Introduction to using Typescript in NodeJS Express Server app - Creating a sample application.