1. 新建 :
2. 安装依赖 :
npm init
npm init @types/koa koa koa-controllers --save
npm init typescript ts-node --save
3. 修改ts配置 :
/* tsconfig.json 配置 */
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"moduleResolution": "node",
"outDir": "./dist",
"noImplicitThis": true,
"strictNullChecks": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"include": [
"./src/**/*"
]
}
4. app.ts :
import Koa = require('koa');
import { useControllers } from 'koa-controllers';
const app = new Koa();
useControllers(app, __dirname + '/controllers/*.ts', {
multipart: {
dest: './uploads'
}
});
app.listen(8080);
5. controllers/MainController.ts :
import * as Koa from 'koa';
import { Controller, Get, Ctx, } from 'koa-controllers'
@Controller
export default class MainController {
@Get('/')
public async index(@Ctx ctx: Koa.BaseContext) {
ctx.body = 'Hello';
}
@Get('/user')
public async user(@Ctx ctx: Koa.BaseContext) {
ctx.body = '用户中心'
}
}
6. 启动app :
.\node_modules\.bin\ts-node .\src\app.ts
// 访问 localhost:8080