Create project structure and install nessess
1mkdir -p ~/code/exercise/ts-demo && cd "$_"
2npm init
3mkdir src
4touch tsconfig.json
5npm i --save-dev @types/node
6npm i --save-dev @types/express
7npm i --save-dev @types/mocha
8npm i express
9npm i nodemon
The src/App.ts
content
1import * as express from 'express'
2
3class App {
4 public express
5
6 constructor () {
7 this.express = express()
8 this.mountRoutes()
9 }
10
11 private mountRoutes (): void {
12 const router = express.Router()
13 router.get('/', (req, res) => {
14 res.json({
15 message: 'Hello World!'
16 })
17 })
18 this.express.use('/', router)
19 }
20}
21
22export default new App().express
The src/index.ts
content
1import app from './App'
2
3const port = process.env.PORT || 3000
4
5app.listen(port, (err) => {
6 if (err) {
7 return console.log(err)
8 }
9
10 return console.log(`server is listening on ${port}`)
11})
And the package.json
like following
1{
2 "name": "express-demo",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "scripts": {
7 "build": "tsc",
8 "dev": "tsc --watch & nodemon dist",
9 "test": "tsc && mocha dist/**/*.spec.js",
10 "lint": "eslint src --ext ts",
11 "tsc": "tsc"
12 },
13 "author": "",
14 "license": "ISC",
15 "devDependencies": {
16 "@types/express": "^4.17.17",
17 "@types/mocha": "^10.0.1",
18 "@types/node": "^20.2.3"
19 },
20 "dependencies": {
21 "express": "^4.18.2",
22 "nodemon": "^2.0.22"
23 }
24}
Build and run
1npm run tsc
2npm run dev