TypeScript 3 + Koajs + Node.js
自NodeJS早期以來,Express一直是NodeJS開發人員事實上的標準Web框架。
但是,JavaScript在過去幾年中已經走過了漫長的道路,像promises和async函式這樣的功能使得構建更小,更強大的Web框架成為可能。
Koa就是這樣一個框架。
它由Express背後的團隊構建,以利用最新的JavaScript和NodeJS功能,特別是非同步功能。
與Express和其他node框架(如Hapi)不同,Koa不需要使用回撥。
這消除了難以跟蹤的錯誤的巨大潛在來源,並使框架非常容易為新開發人員選擇。
在本文中,我將向您介紹如何使用Koa和TypeScript來開發新的Web應用程式專案
第一步、安裝和配置
Koa需要一個具有非同步功能支援的Node版本,因此在開始之前確保安裝了Node 8.x(或更高版本)。
Node 8將於2017年10月成為新的長期支援版本,因此它是啟動新專案的絕佳選擇。
我們現在將建立一個安裝了以下內容的新node專案:
1. Koa
2. Koa Router
3. TypeScript
4. TS-Node 和 Nodemon(用於在開發期間自動構建和重啟)
為專案建立一個新資料夾,然後執行以下命令:
npm init# and follow the resulting prompts to set up the project npm i koa koa-router npm i --save-dev typescript ts-node nodemon npm i --save-dev @types/koa @types/koa-router
現在,在專案的根目錄中,建立一個新的tsconfig.json檔案並新增以下內容:
{ "compilerOptions": { "module": "commonjs", "target": "es2017", "noImplicitAny": true, "outDir": "./dist", "sourceMap": true }, "include": [ "./src/***/*", ] }
請注意,我們將TypeScript配置為轉換為ES2017 - 這可確保我們利用Node的本機async/await功能。
第二步、建立伺服器
由於Koa的核心是微框架,因此啟動和執行它非常簡單。在專案目錄中,建立一個src資料夾,在其中建立一個新檔案:server.ts,其中包含以下內容:
import * as Koa from 'koa'; import * as Router from "koa-router"; const app = new Koa(); const router = new Router(); router.get('/*', async (ctx) => { ctx.body = "Hi TS"; }) app.use(router.routes()); app.listen(8080); console.log("Server running on port 8080");
第三步、使用Nodemon和TS-Node執行伺服器
在開發過程中,每次進行更改時都要記住重新啟動伺服器會很麻煩,所以我想設定我的伺服器端專案以自動重新啟動程式碼更改。
為此,我們將向我們的專案新增watch-server npm指令碼。
為此,請將以下內容新增到package.json的"scripts"部分:
"watch-server": "nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts"
現在開始新的TypeScript Koa專案,只需執行以下操作即可
npm run watch-server
您應該看到以下輸出:
> [email protected] watch-server /Users/durban/nodejs/ts_node_koa_blog > nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts [nodemon] 1.18.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching: src/***/* [nodemon] starting `ts-node ./src/server.ts` Server running on port 8080
現在您應該能夠在瀏覽器中訪問http//localhost:8080/ :)
第四步、構建應用程式 - 新增中介軟體
主要的Koa庫只包含基本的HTTP功能。
要構建完整的Web應用程式,我們需要新增適當的中介軟體,例如Logging, Error Handling, CSRF Protection等。在Koa中,中介軟體本質上是一堆函式,通過app.use()建立。
收到Web請求後,它將傳遞給堆疊中的第一個函式。
該函式可以處理請求,然後可選地將其傳遞給下一個中介軟體函式。
讓我們將上面的示例擴充套件為包含一箇中間件函式,該函式將每個Web請求的URL記錄到控制檯:
import * as Koa from 'koa'; import * as Router from "koa-router"; const app = new Koa(); app.use(async (ctx, next) => { // Log the request to the console console.log("Url: ", ctx.url); // Pass the request to the next middleware function await next(); }) const router = new Router(); router.get('/*', async (ctx) => { ctx.body = "Hi TS"; }) app.use(router.routes()); app.listen(8080); console.log("Server running on port 8080");
在上面的示例中,我們現在定義兩個中介軟體函式:
1. 第一個中介軟體函式從請求上下文(ctx.url)獲取Url,並使用console.log()將其輸出到控制檯
2. 然後該函式await next(),告訴Koa將請求傳遞給堆疊中的下一個中介軟體函式
3. 第二個中介軟體函式來自koa-router - 它使用請求的url來匹配我們通過router.get()配置的路由現在,當您在瀏覽器中訪問http://localhost:8080/時,您應該看到類似於以下內容的輸出:
> [email protected] watch-server /Users/durban/nodejs/ts_node_koa_blog > nodemon --watch 'src/***/*' -e ts,tsx --exec 'ts-node' ./src/server.ts [nodemon] 1.18.4 [nodemon] to restart at any time, enter `rs` [nodemon] watching: src/***/* [nodemon] starting `ts-node ./src/server.ts` Server running on port 8080 Url:/ Url:/ Url:/blog Url:/blog
第五步、標準中介軟體
顯然,你真的不想為你的網路應用重新發明輪子。
根據您要建立的應用程式型別,以下中介軟體可能很有用:
Koa路由器https://github.com/alexmingoia/koa-router Koa Body Parser(用於JSON和Form Data支援)https://github.com/dlau/koa-body Koa Cross-Site-Request-Forgery(CSRF)預防https://github.com/koajs/csrf Koa Examples(許多有用的東西,包括錯誤處理)https://github.com/koajs/examples
我已經建立了一個基本的TypeScript和Koa專案。可以進行後面自己感興趣的開發了。