[Express] Using TypeScript
TypeScript 的型別和屬性宣告, 確實能減少不少 JavaScript 開發時小小疏失導致的錯誤, 尤其在 API Server 時, 接收客戶端資料若沒有驗證型別, 可能會導致意外錯誤發生. 利用 TypeScript 開發 API Server 是個不錯的主意.
建立專案
和所有 Node.js 專案一樣, 使用 npm 初始化新的 package.json
不會有錯.
npm init
yarn init
npm
和yarn
指令依個人習慣擇一即可.
會需要填入一些專案的相關資訊:
- package name 輸入專案名稱, 預設使用資料夾名稱
- version 版本號, 預設 1.0.0
- description 專案的詳細介紹, 可不填
- entry point 專案的程式載入點, 預設 index.js
- test command 專案測試用的指令, 可不填
- git repository 輸入 git 遠端位址, 可不填
- keywords 輸入專案相關的關鍵字, 可不填
- author 輸入專案作者名稱, 可不填
- license 授權相關, 預設 ISC
--yes
若專案不會有發布 npm 的需求, 只想快速產生 package.json
來管理套件.
可加上 --yes
快速建立預設值內容如下.
{
"name": "express-typescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC"
}
TypeScript
透過 npm 進行安裝 TypeScript. 依實際需求, 通常建議全域安裝.
npm i -g typescript
yarn global add typescript
若真的沒有其他 TypeScript 專案開發需求, 以專案角度來說, TypeScript 只是開發上需要, 歸屬於開發依賴套件即可.
npm i typescript --save-dev
yarn add typescript --dev
tsconfig.json
要透過 TypeScript 指令初始化 tsconfig.json
$ tsc init
$ npx tsc init
Created a new tsconfig.json with:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
自從多了
npx
之後, 部分 CLI 套件指令可以直接透過 npx 來執行. npx 會自動管理與處理套件依賴的下載等, 不一定需要安裝全域套件.
專案資落夾會多一個 tsconfig.json
, 這個檔案是用來設定編譯選項的. 詳細設定可參考 官方文件
tsconfig.json
{
"compilerOptions": {
"incremental": true, // 啟用增量編譯
"target": "ES2017", // 編譯成指定的 JavaScript 版本
"module": "commonjs", // 指定編譯成何種模組
"declaration": true, // 產生 '.d.ts' 檔
"sourceMap": true, // 產生 '.map' 檔
"outDir": "./dist", // 指定編譯後的檔案存放點
"rootDir": "./src", // 載入點的位置
"removeComments": true, // 移除註解
"strict": true, // 採用嚴格模式
"baseUrl": "./src", // 指定匯入檔案的基準路徑
"esModuleInterop": true, // 兼容模組
"experimentalDecorators": true, // 啟用裝飾器
"emitDecoratorMetadata": true // 提供裝飾器 metadata
},
"include": ["src/**/*.ts"], // 納入編譯範圍
"exclude": ["node_modules", "dist"] //不納入編譯範圍
}
Express
安裝 Express:
$ npm i express
$ yarn add express
yarn add v1.22.19
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
[4/4] 🔨 Building fresh packages...
success Saved 1 new dependency.
info Direct dependencies
└─ express@4.18.1
info All dependencies
└─ express@4.18.1
✨ Done in 0.88s.
若指令順利執行完畢, 可看到 package.json
中的 dependencies 多了 express, 表示安裝成功.
接著要取得 Node.js 與 express 的 type 定義檔, 在開發時能夠清楚知道有哪些功能可以使用:
npm i @types/node @types/express --save-dev
yarn add @types/node @types/express -D
index.js
TypeScript .ts
原始檔需經編譯後才可執行, 為方便編譯設置, 建議放 src
資料夾下.
├── src
| └── index.ts
├── package.json
└── tsconfig.json
index.ts
import express from 'express';
const app = express();
app.get('/', (req, res, next) => {
res.send('Hello, World!!');
});
app.listen(3000, () => console.log('http server is running at port 3000.'));