9b9387

9b9387

如灰尘保佑的礼物

© 2024

开发笔记(1)——koa环境搭建

koa环境搭建

安装node.js

brew install node

创建项目,项目名叫dudu

mkdir dudu
cd dudu
npm init

添加koa模块

npm install -save koa

编写index.js

const Koa = require('koa')
const app = new Koa()

app.use( async ( ctx ) => {
  ctx.body = 'hello koa2'
})

app.listen(3000)
console.log('start-quick is starting at port 3000')

运行

npm start // node index.js

TypeScript

安装TypeScript

npm install -g typescript ts-node nodemon

npm install -D @types/node @types/koa

生成tsconfig.json

tsc --init

监视代码变更

  "scripts": {
    "dev": "tsc -w | nodemon ."
  },

更新代码 src/application.ts

import Koa, { Context } from 'koa';
import { Server } from 'http';

export class Application {
    private app: Koa;
    
    constructor() {
        this.app = new Koa();

        const server = async (ctx: Context, next: any ) => {
            if(ctx.url == "/")
            {
                ctx.body = "Running..."
            }
            if(ctx.url === '/test')
            {
                ctx.body = {info:'this is test message.'}
            }
            next && next()
        }
        this.app.use(server)
    }
   
    public run(port: number) : Server {
        console.log('start-quick is starting at port 3000')
        return this.app.listen(port)
    }
}

运行

npm run dev