yyman001 / blog

日常疑问记录解答
5 stars 0 forks source link

vs code 调试 ts koa 源码 #80

Open yyman001 opened 4 years ago

yyman001 commented 4 years ago

版本

{
    "koa": "^2.11.0",
    "koa-router": "^8.0.8",
    "@types/koa-router": "^7.4.1",
    "@types/koa": "^2.11.3",
    "ts-node": "^8.10.2",
    "typescript": "^3.9.5"
}

tsconfig.json 配置

详细编译参数文档

{
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    // 如果开启这个属性, 编译会把所有js文件都归入编译范围
    "allowJs": false,
    "target": "es2017",
    "module": "commonjs",
    "sourceMap": true,
    "alwaysStrict": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "listEmittedFiles": true,
    "noImplicitReturns": true,
    "strictNullChecks": true,
    "declaration": true
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules",
    ".vscode",
    ".idea",
    "test"
  ]
}

launch.json 运行配置

更多配置信息请移步ts-node的github api 文档处

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "debug ts",
      "args": [
       // 调试入口文件或指定调试文件
        "${workspaceFolder}/src/app.ts"
      ],
      "runtimeArgs": [
        "-r",
        "ts-node/register/"
      ],
      "env": {
        "NODE_ENV": "dev"
      }
    }
  ]
}

自动编译任务

方式一:

在命令行输入以下命令或 在 vs code 点击 终端-运行任务-tsc: 监视 -tsconfig.json (快捷键: Ctrl + Shift + B)

// 监听定义好的tsconfig.json
tsc -w

其他方式不讨论了, 这里只讨论vs code的

示例:

数据类型校验需要使用 import * as Koa from 'koa', 不做可以使用原来的const Koa = require('koa') 方式

// app.ts
const Koa = require('koa')
const KoaRouter = require('koa-router')
const router = new KoaRouter()
const AppServer = new Koa()
const PORT = 3456

import {a} from './a'

router.get('/', a)

AppServer
  .use(router.routes())
  .use(router.allowedMethods())

AppServer.listen(PORT, () => {
  console.log(`koa server port:${PORT} starting...`)
})
// a.ts
import * as Koa from 'koa'

export async function a (ctx: Koa.Context, next: any) {
  const {request} = ctx
  ctx.body = {
    query: request.query
  }
}

资料

TypeScript教程