詳細實作方式以及源碼下載下傳請前往 https://www.passerma.com/article/70
"koa2+typescript環境搭建
1.安裝koa2腳手架
全局安裝koa2腳手架 npm install -g koa-generator
2.使用腳手架建立項目
koa2 project
後面的project表示項目的名稱,我這裡以koa2-ts項目名為指令 koa2 koa2-ts 舉例,建立完成,生成以下目錄
進入項目,安裝依賴
cd project
npm install
3.建立typescript環境
整理檔案夾項目,開始建構typescript環境
1).重新整理檔案
建立src檔案夾,将routes,bin目錄移動至src目錄下,作為ts編譯的入口
将app.js也移入到src目錄
将bin下的www檔案重命名為www.js
2).建立并配置tsconfig.json檔案
使用 tsc -init ,會在目前目錄建立tsconfig.json檔案,修改配置檔案
将compilerOptions裡的allowJs解開注釋設定為true
将compilerOptions裡的outDir解開注釋設定為./build
将compilerOptions裡的rootDir解開注釋設定為./src
将compilerOptions裡的esModuleInterop解開注釋設定為true
在compilerOptions同級增加exclude屬性,設定值如下數組
[
"node_modules",
"views",
"public",
"build"
]
去掉無用項,得到最終配置項
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"allowJs": true,
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"exclude": [
"node_modules",
"views",
"public",
"build"
]
}
安裝typescript
npm i typescript -D
3).修改package.json檔案
先安裝項目啟動所需依賴兩個的檔案:nodemon,concurrently
npm i nodemon concurrently -D
增加對應的scripts腳本指令,設定完成後如下
"scripts": {
"dev:tsc": "tsc -w",
"dev:nodemon": "nodemon build/www",
"dev": "tsc && concurrently npm:dev:*",
"start": "tsc && node build/www"
}
4).修改app.js檔案内容
引入path子產品,修改靜态檔案以及模闆檔案目錄
let staticPath = path.join(__dirname, '../public'); // 靜态位址
let viewsPath = path.join(__dirname, '../views'); // 模闆位址
app.use(require('koa-static')(staticPath))
app.use(views(viewsPath, {
extension: 'pug'
}))
5).啟動項目,預設端口是3000
npm run dev 啟動開發環境,每次修改完成都會實時重新開機項目
npm start 啟動生産環境,隻會啟動一次項目
浏覽器通路http://localhost:3000/,成功啟動項目
4.typescript環境下編寫接口
在routes下建立tsRoutes.ts檔案
引入koa-router,現在可以使用import文法引入了,同時需要安裝koa-router的類型定義檔案 npm install @types/koa-router -D
import Router from 'koa-router'
const router = new Router();
router.prefix('/tsRoutes')
router.get('/', async (ctx) => {
ctx.body = {
data: [1, 2, 3]
};
})
export default router
在app.js引入該路由檔案即可
浏覽器通路http://localhost:3000/tsRoutes,成功解析ts檔案
5.總結
代碼已上傳GitHub,連結koa2+typescript環境搭建
詳細實作方式以及源碼下載下傳請前往 https://www.passerma.com/article/70