接上文
1、安装 koa
yarn add koa koa-router koa-static
yarn add @types/koa @types/koa-router @types/koa-static --dev
2、修改 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}`);
3、新建路由文件夹 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 }
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:目录结构