สร้างโปรเจ็ค Express + TypeScript

TypeScript Mar 22, 2023

วิธีการเริ่มโปรเจ็คด้วยการใช้ Express.js กับ TypeScript ซึ่งช่วงหลังๆ ผมก็แทบไม่ค่อยได้จับงาน Backend ซักเท่าไหร่ และไม่ได้ใช้ Express แล้ว วันนี้ว่างๆ ก็เลยลองขึ้นโปรเจ็ค Express เล่นๆ ดูด้วย TypeScript ก็เลยนำมาเขียนเป็นบล็อกเอาไว้

Express - Node.js web application framework
JavaScript With Syntax For Types.
TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.

เริ่มต้นสร้างโปรเจ็คด้วยคำสั่ง

npm init -y

ติดตั้ง Express

npm install express

ติดตั้ง TypeScript และ Types ของ express และ node

npm install -D typescript @types/node @types/express ts-node

สร้างไฟล์ tsconfig.json ด้วยคำสั่ง init

tsc --init

จะได้ไฟล์ tsconfig.json ขึ้นมา เพิ่ม outdir  เป็น dist เวลาที่ build typescript จะให้มัน generate file JavaScript ไปที่โฟลเดอร์ dist

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist"
  }
}

สร้างไฟล์ src/app.ts ขึ้นมา เป็น Express แบบง่ายๆ ด้วย TypeScript

// src/app.ts
import express, { Express, Request, Response } from 'express'

const app: Express = express()

const port: number = 3000

app.get('/', (req: Request, res: Response) => {
  res.json({
    message: 'Hello Express + TypeScirpt!!',
  })
})

app.listen(port, () => console.log(`Application is running on port ${port}`))

เพิ่ม Script ใน package.json สำหรับ build และ start Server

  • start - สำหรับรัน express ที่ build แล้ว
  • build - เอาไว้ compile TypeScript
  • start:ts - เอาไว้รัน express แบบไม่ต้อง compile ด้วย ts-node (dev mode)
// package.json
{
  "scripts": {
    "start:ts": "ts-node src/app.ts",
    "start": "node dist/app.js",
    "build": "tsc",
  }
}
Note: ตัวโปรเจ็คเป็นแบบง่ายๆนะครับ การนำไปใช้ Production ยังต้องมี config เพิ่ม รวมถึงยังขาด config อีกหลายส่วนครับ

ทีนี้ เราก็แค่ build และ start ก็จะได้โปรเว็บ Express + TypeScript แบบง่ายๆแล้ว

npm run build
npm start

Done!

หรือตัวเลือก ใครอยากได้แบบ generator ลองใช้ตัวนี้ได้ครับ

GitHub - seanpmaxwell/express-generator-typescript: Create a new express app similar to express-generator but with TypeScript
Create a new express app similar to express-generator but with TypeScript - GitHub - seanpmaxwell/express-generator-typescript: Create a new express app similar to express-generator but with TypeSc…

Happy Coding ❤️

Tags

Chai Phonbopit

เป็น Web Dev ทำงานมา 10 ปีหน่อยๆ ด้วยภาษา JavaScript, Node.js, React, Vue และปัจจุบันกำลังสนใจ Web3, Crypto และ Blockchain เขียนบล็อกที่ https://devahoy.com