隨着應用的龐大,項目中 javascript 的代碼也會愈來愈臃腫,團隊之間的協做也會遇到難題,若是不一直看 api 文檔,很難知道團隊其餘成員寫的方法須要什麼參數,返回結果又是什麼。javascript
解決的方案有不少,這裏不比較各類方法的優劣,僅說下選擇 typescript 的考慮:一、接受程序好,ts 文件中能夠直接寫 javascript 代碼,平滑過渡;二、vs code 的提示夠好。java
下面開始一步一步地搭建 web 服務( windows環境 )node
1、typescript 開發環境如何配置es6
一、初始化項目web
yarn init -y
二、安裝 typescripttypescript
yarn add typescript @types/node --dev
三、配置 typescript 編譯環境shell
在項目根目錄下新建文件 tsconfig.json數據庫
{ "compilerOptions": { "target": "es2017", "outDir": "./dist", "module": "commonjs", "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es6" ], "noImplicitAny": false, "sourceMap": false, "allowJs": true }, "include": [ "./src/**/*" ], "exclude": [ "node_modules" ] }
四、測試json
新文件夾 src 並添加文件 server.ts,在文件中寫下以下代碼windows
console.log("Hello TypeScript");
五、編譯
.\node_modules\.bin\tsc
六、運行
node ./dist/server.js
若是能看到控制檯輸出
Hello TypeScript
恭喜你,typescript 環境配置成功!
2、集成 web 開發框架 koa
一、安裝 koa 及 types
yarn add koa koa-router koa-static @types/koa @types/koa-router @types/koa-static
二、修改 server.ts 文件,輸入以下內容
/* * @Description: 後臺服務入口 * @version: 0.1.0 */ import * as Koa from 'koa'; import * as koaStatic from 'koa-static' import { router } from './router'; const app = new Koa(); /** * @name: 設置靜態資源目錄 * @param : undefined * @return : undefined */ app.use(koaStatic('./www')); /** * @name: 使用路由 * @param : undefined * @return : undefined */ app.use(router.routes()); /** * @name: 服務端口 * @param : undefined * @return : undefined */ const httpPort = 8080 app.listen(httpPort); console.log(`Http Server running on port ${httpPort}`);
三、新建路由文件夾 router 及文件 index.ts
/* * @Description: 後臺路由組件 * @version: 0.1.0 */ import * as Router from 'koa-router'; const router = new Router(); router.get('/*', async (ctx) => { ctx.body = 'Hell koa'; }) export { router }
四、編譯、運行
打開瀏覽器,輸入 http://localhost:8080
若是能看到 Hello Koa,恭喜你,koa 的集成成功。一個簡單的 web 服務就實現了。
後面若是有機會就講下如何操做數據庫。
目錄結構以下: