接上文
1、安装 koa
yarn add koa koa-router koa-static
yarn add @types/koa @types/koa-router @types/koa-static --dev
2、修改 server.ts
1 /* 2 * @Description: 后台服务入口 3 * @version: 0.1.0 4 */ 5 6 import * as Koa from 'koa'; 7 import * as koaStatic from 'koa-static' 8 import { router } from './router'; 9 10 const app = new Koa(); 11 12 /** 13 * @name: 设置静态资源目录 14 * @param : undefined 15 * @return : undefined 16 */ 17 app.use(koaStatic('./www')); 18 19 /** 20 * @name: 使用路由 21 * @param : undefined 22 * @return : undefined 23 */ 24 app.use(router.routes()); 25 26 /** 27 * @name: 服务端口 28 * @param : undefined 29 * @return : undefined 30 */ 31 const httpPort = 8080 32 33 app.listen(httpPort); 34 35 console.log(`Http Server running on port ${httpPort}`);
3、新建路由文件夹 router 及文件 index.ts
1 /* 2 * @Description: 后台路由组件 3 * @version: 0.1.0 4 */ 5 import * as Router from 'koa-router'; 6 7 const router = new Router(); 8 9 router.get('/*', async (ctx) => { 10 ctx.body = 'Hell koa'; 11 }) 12 13 export { router }
4、文件改动之后,服务程序能够自动重启,安装 nodemon、concurrently
yarn add nodemon concurrently --dev
5、修改 package.json
"main": "./dist/server.js", "scripts": { "server": "nodemon main", "dev": "tsc && concurrently "npm run tsc" "npm run server"", "build": "tsc", "tsc": "tsc -w" }
6、启动服务
yarn run dev
7、打开浏览器,输入 http://localhost:8080
至此koa的集成完成。
PS:目录结构