Step 1
npm init //初始化項目時最好將提示的字段都填上兰绣,否則在下面的npm install時有警告
// 安裝依賴
npm i --save koa koa-router tslib
npm i --save-dev typescript nodemon
npm i --save-dev @types/koa @types/koa-router
tslib依賴用于在
tsconfig.json
的target選項設(shè)置為es2017以下時添加async/await等支持https://github.com/Microsoft/tslib
01.PNG
02.PNG
Step 2
添加tsconfig.json
配置娜汁,為了使用原生的Async/Await
芯勘,可以將編譯的目標(biāo)版本target
設(shè)置為"es2017"
進(jìn)一步地锻煌,可參考http://www.reibang.com/p/912747f07025
{
"compilerOptions": {
"allowJs": true,
// 允許編譯javascript文件
"allowUnreachableCode": true,
// 不報告執(zhí)行不到的代碼錯誤硼补。
"allowUnusedLabels": false,
// 不報告未使用的標(biāo)簽錯誤
"alwaysStrict": true,
// 以嚴(yán)格模式解析并為每個源文件生成"use strict"語句
"baseUrl": ".",
// 解析非相對模塊名的基準(zhǔn)目錄
"checkJs": true,
// 在javascript文件中報告錯誤
// 只有當(dāng)"allowJs"置為true時才能指定
// "composite": true,
// Ensure TypeScript can determine
// where to find the outputs of the referenced project to compile project.
"declaration": true,
// 生成相應(yīng)的.d.ts文件
// 不能與isolatedModules同時指定
"declarationDir": "build/declaration",
// 生成聲明文件的輸出路徑
// 只有當(dāng)"declaration"置為true時才能指定
// 且不能與outFile同時指定
"disableSizeLimit": true,
// 禁用JavaScript工程體積大小的限制
"downlevelIteration": true,
// Provide full support for
// iterables in for..of, spread and destructuring
// when targeting ES5 or ES3
"diagnostics": true,
// 顯示診斷信息
"emitDecoratorMetadata": true,
// 給源碼里的裝飾器聲明加上設(shè)計類型元數(shù)據(jù)。
// Emit design-type metadata for decorated declarations in source.
"experimentalDecorators": true,
// 啟用實驗性的ES裝飾器
"extendedDiagnostics": true,
// Show verbose diagnostic information
"forceConsistentCasingInFileNames": true,
// 禁止對同一個文件的不一致的引用
"importHelpers": false,
// 從 tslib 導(dǎo)入輔助工具函數(shù)(如 __extends撇寞, __rest等)
// Import emit helpers (e.g. '__extends', '__rest', etc..) from tslib.
// Requires TypeScript version 2.1 or later.
// 默認(rèn)為false
"incremental": true,
// 啟用增量編譯
// default: true if composite is on, false otherwise
// Enable incremental compilation by
// reading/writing information from prior compilations to a file on disk.
// This file is controlled by the --tsBuildInfoFile flag.
"inlineSourceMap": true,
// 生成單個sourcemaps文件礁芦,而不是將每sourcemaps生成不同的文件。
"inlineSources": true,
// 將代碼與sourcemaps生成到一個文件中罢吃,
// 要求同時設(shè)置了 --inlineSourceMap或 --sourceMap屬性楚午。
"isolatedModules": true,
// 將每個文件作為單獨的模塊進(jìn)行轉(zhuǎn)譯(Transpile)
// (與“ts.transpileModule”類似)
// 不可與outFile或declaration同時指定
"jsx": "react",
// 在.tsx文件里支持JSX
"lib": [
"dom",
"es2015",
"es2016",
"es2017",
"es2018"
],
// 編譯過程中需要引入的庫文件的列表。
// Specify library file to be included in the compilation.
// Requires TypeScript version 2.0 or later.
"listEmittedFiles": false,
// 打印出編譯后生成文件的名字
"listFiles": false,
// 編譯過程中打印文件名
"module": "CommonJS",
// 指定生成哪個模塊系統(tǒng)代碼:
// "None"尿招, "CommonJS"矾柜, "AMD"阱驾,
// "System", "UMD"怪蔑, "ES6"或 "ES2015"
// 只有 "AMD"和 "System"能和 --outFile一起使用里覆。
// "ES6"和 "ES2015"可使用在目標(biāo)輸出為 "ES5"或更低的情況下
// 默認(rèn)為(target === "ES6" ? "ES6" : "commonjs")
"moduleResolution": "node",
// 決定如何處理模塊。"node"對應(yīng)于Node.js/io.js
"noEmitHelpers": false,
// 不在輸出文件中生成用戶自定義的幫助函數(shù)代碼缆瓣,如 __extends
// Do not generate custom helper functions like __extends in compiled output.
// 默認(rèn)為false
"noErrorTruncation": true,
// 不截斷錯誤消息
"noFallthroughCasesInSwitch": true,
// 報告switch語句的fallthrough錯誤(即不允許switch的case語句貫穿)
"noImplicitAny": true,
// 在表達(dá)式和聲明上有隱含的any類型時報錯
"noImplicitReturns": true,
// 不是函數(shù)的所有返回路徑都有返回值時報錯
"noImplicitThis": true,
// 當(dāng)this表達(dá)式的值為any類型的時候喧枷,生成一個錯誤
"noImplicitUseStrict": false,
// 模塊輸出中是否不包含"use strict"指令
"noStrictGenericChecks": false,
// 是否禁用在函數(shù)類型里對泛型簽名進(jìn)行嚴(yán)格檢查
"noUnusedLocals": true,
// 若有未使用的局部變量則拋錯
"noUnusedParameters": true,
// 若有未使用的參數(shù)則拋錯
"outDir": "build/distribution",
"paths": {
"*": [
"node_modules/*"
]
},
"preserveConstEnums": true,
// 保留const和enum聲明
"pretty": true,
// 使用顏色和上下文給錯誤和信息添加樣式(實驗性)
"removeComments": true,
// 刪除所有注釋,除了以/!*開頭的版權(quán)信息
"sourceMap": false,
// 生成相應(yīng)的 .map文件
// 不能與inlineSourceMap同時指定
"strict": true,
// 啟用所有嚴(yán)格類型檢查選項弓坞。
// 啟用strict相當(dāng)于啟用
// noImplicitAny,noImplicitThis,alwaysStrict隧甚,
// strictBindCallApply,
// strictNullChecks,
// strictFunctionTypes,
// strictPropertyInitialization
"strictNullChecks": true,
// 在嚴(yán)格的null檢查模式下,
// null和undefined值不包含在任何類型里渡冻,
// 只允許用它們自己和any來賦值(undefined可以賦值到void除外)
"strictFunctionTypes": false,
//是否禁用函數(shù)參數(shù)雙向協(xié)變檢查
"target": "ES3",
// 指定ECMAScript目標(biāo)版本
// "ES3"(默認(rèn))戚扳, "ES5", "ES6"/"ES2015"族吻,
// "ES2016"帽借, "ES2017"或 "ESNext"
"traceResolution": false
// 生成模塊解析日志信息
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
Step 3:創(chuàng)建Koa HelloWorld
我們在src
目錄下創(chuàng)建文件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 = 'Hello Koa2 with TypeScript!';
});
app.use(router.routes());
app.listen(3000);
console.log('Server running on port 3000');
Step 4:設(shè)置編譯運行及熱更新
在package.json
中設(shè)置編譯運行及熱更新啟動命令
"scripts": {
"boot-run": "tsc && node dist/server.js",
"test": "nodemon --watch src -e ts,tsx --exec \"npm run boot-run\" "
}
其中npm run boot-run
用于編譯運行,npm test
(或npm run test
)用于開發(fā)過程中使用nodemon 監(jiān)視源文件變化以熱更新超歌。完整的package.json
例子如下砍艾。
{
"name": "koa2",
"version": "2019.9.1",
"description": "Koa2 application",
"main": "index.js",
"scripts": {
"boot-run": "tsc && node dist/server.js",
"test": "nodemon --watch src -e ts,tsx --exec \"npm run boot-run\" "
},
"repository": {
"type": "git",
"url": "http://localhost"
},
"author": "",
"license": "MIT",
"dependencies": {
"koa": "^2.8.1",
"koa-router": "^7.4.0",
"tslib": "^1.10.0"
},
"devDependencies": {
"@types/koa": "^2.0.49",
"@types/koa-router": "^7.0.42",
"nodemon": "^1.19.2",
"typescript": "^3.6.3"
}
}
TODO
尚未加入tslint
Reference
-
使用Typescript和Koa構(gòu)建Node應(yīng)用
這篇文章配置nodemon監(jiān)視源文件改變時命令有誤,應(yīng)該使用--watch src
而不是UNIX通配符形式巍举,閱讀nodemon文檔時發(fā)現(xiàn)了這一點 -
nodemon
https://github.com/remy/nodemon#nodemon