DEV Community

Cover image for วิธีการตั้งค่า TypeScript กับ Node.js
Somprasong Damyos
Somprasong Damyos

Posted on • Edited on

11 3

วิธีการตั้งค่า TypeScript กับ Node.js

อัพเดท 2022-07-22

วิธีการตั้งค่าโปรเจคให้สามารถรัน TypeScript ได้ พร้อมกับวิธีการนำไปใช้กับ Express

สิ่งที่ต้องมี

  • Node.js version >= 12
  • npm หรือ yarn

การตั้งค่าโปรเจคให้สามารถรัน TypeScript ได้

  • เริ่มจากสร้างโปรเจคใหม่ และสร้างไฟล์ package.json
mkdir typescript-node
cd typescript-node
npm init -y
Enter fullscreen mode Exit fullscreen mode
  • ติดตั้ง libraries ใน devDepencies

    • typescript เป็นตัวหลักที่ช่วยแปลงจาก TypeScript ไปเป็น JavaScript
    • ts-node เป็นเหมือน dev server ค่อยช่วยแปลงโค้ดจาก TypeScript ไปเป็น JavaScript ในขั้นตอนพัฒนา
    • nodemon ตัวช่วยให้รันโค้ดใหม่อัตโนมัติ เมื่อมีการแก้ไขโค้ด ทำงานร่วมกับ ts-node
npm i -D typescript ts-node nodemon
Enter fullscreen mode Exit fullscreen mode
  • สร้างไฟล์ tsconfig.json โดยใช้คำสั่ง
ืnpx tsc --init
Enter fullscreen mode Exit fullscreen mode

และแก้ไขค่าตามนี้

{
  "compilerOptions": {
-    "target": "es5"
+    "target": "es6" /* กำหนดว่าให้แปลงเป็น js version อะไร */,
    "module": "commonjs" /* กำหนดว่าจะใช้ module แบบไหน */,
+    "moduleResolution": "node" /* บอกใช้กับ Node.js */,
    "esModuleInterop": true /* อนุญาติให้ complie ES6 module เป็น commonjs*/,
    "strict": true /* เปิดใช้ strict type-checking options*/,
+    "outDir": "./dist" /* ระบุโฟลเดอร์ output (JavaScript) */,
+    "rootDir": "./src" /* ระบุโฟลเดอร์ sourcecode (TypeScript) */
  }
}
Enter fullscreen mode Exit fullscreen mode
  • แก้ไข script ไฟล์ package.json

    • dev สำหรับรันโค้ดในโหมดพัฒนา จะทำการ reload อัตโนมัติเมื่อแก้ไขโค้ด
    • build สำหรับแปลงไฟล์เป็น JavaScript สำหรับการนำไปใช้งานจริง
"scripts": {
  "dev": "nodemon",
  "build": "tsc --project ./"
},
Enter fullscreen mode Exit fullscreen mode
  • และสร้างไฟล์ nodemon.json
{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "ts-node ./src/index.ts"
}
Enter fullscreen mode Exit fullscreen mode

ทดสอบโค้ด TypeScript

  • สร้างไฟล์ src/index.ts
const geeting = (name: string) => {
  console.log(`Hello ${name} from TypeScript.`);
};

geeting('Ball');
Enter fullscreen mode Exit fullscreen mode
  • รัน npm run dev
> typescript-node@1.0.0 dev D:\workspaces\playgounds\typescript-node
> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src\**\*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts`
Hello Ball from TypeScript.
[nodemon] clean exit - waiting for changes before restart
Enter fullscreen mode Exit fullscreen mode
  • ทดลองแก้ไขชื่อ nodemon ก็จะ restart ให้อัตโนมัติ
[nodemon] restarting due to changes...
[nodemon] starting `ts-node ./src/index.ts`
Hello Stamp from TypeScript.
[nodemon] clean exit - waiting for changes before restart
Enter fullscreen mode Exit fullscreen mode
  • ทดสอบ build โดยรันคำสั่ง npm run build ก็ได้จะได้โฟลเดอร์ dist ออกมา และมีไฟล์ index.js อยู่ข้างใน
// dist/index.js
'use strict';
const geeting = (name) => {
  console.log(`Hello ${name} from TypeScript.`);
};
geeting('Stamp');
Enter fullscreen mode Exit fullscreen mode

วิธีตั้งค่า TypeScript กับ Express

  • ติดตั้ง Express รัน npm i express

  • สร้าง Express Server ง่ายๆ ที่ไฟล์ src/index.ts

import express from 'express';

const app = express();

const PORT = 8000;

app.get('/', (req, res) => res.send('Express + TypeScript Server'));

app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode
  • ทดสอบรัน npm run dev จะพบว่าไม่สามารถรันได้ เนื่องจาก มันไม่รู้จัก type นั่นเอง

  • แก้ไขโดยการติดตั้ง @types ที่ต้องการเพิ่มเข้าไป

npm i -D @types/node @types/express
Enter fullscreen mode Exit fullscreen mode

ถ้าใช้ bodyParser ก็ต้องติดตั้ง @types/body-parser เพิ่มด้วย

  • เมื่อรองรันใหม่อีกครั้งก็จะสามารถรันได้แล้ว
npm run dev

> typescript-node@1.0.0 dev D:\workspaces\playgounds\typescript-node
> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src\**\*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts`
Server is running at http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

ยังๆ... ไม่หมด

เนื่องจากเราเขียนแบบ TypeScript แต่โค้ดข้างต้นยังไม่ได้ถูกกำหนด type ให้ถูกต้องเลย ดังนั้นเรามากำหนด type ให้ถูกต้องการ ดังนี้

  • app ต้องมี type เป็น Application
  • req ต้องมี type เป็น Request
  • res ต้องมี type เป็น Response
import express, { Application, Request, Response } from 'express';

const app: Application = express();

const PORT: number = 8000;

app.get('/', (req: Request, res: Response) => {
  res.send('Express + TypeScript Server');
});

app.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

เท่านี้ก็เรียบร้อยแล้ว

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (2)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

จริงๆ tsc init ก็ได้ ไม่ต้องเขียน tsconfig.json เอง แถมยัง update ตาม version TypeScript

npx tsc init # or
yarn tsc init
Enter fullscreen mode Exit fullscreen mode

ส่วนเรื่อง nodemon ส่วนใหญ่ เราจะใช้ ts-node-dev

Collapse
 
somprasongd profile image
Somprasong Damyos

ขอบคุณครับ จริงๆ ตอนแรกใช้ npx tsc --init สร้างมาก่อน แล้วแก้ไขไฟล์เอาแต่ตอนเขียนลืมบอกไป

ส่วน ts-node-dev ไว้ลองศึกษาเพิ่มดูครับ ขอบคุณครับ

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay