目的
用typescript开发node server程序,并做到hot-reload和ts文件上的debug
技术栈
问题1:什么是routing-controller
先感受一下routing-controller
import {JsonController, Get, Post, Param, Delete, Body} from "routing-controllers";import {Service} from "typedi";import {CategoryRepository} from "../repository/CategoryRepository";import {Category} from "../model/Category";@Service()@JsonController()export class CategoryController { constructor(private categoryRepository: CategoryRepository) { } @Get("/categories") all(): Promise{ return this.categoryRepository.findAll(); } @Get("/categories/:id") one(@Param("id") id: number): Category { return this.categoryRepository.findOne(id); }}
一股满满的SpringMVC既视感,对于开发过JavaWeb的我来说上手很快,
问题2:如何调试
调试的初级方法是print、console,进阶就是下断点debug,我们是不是能把断点下在ts文件里而不是编译后的js里呢?当然可以。
配置launch.json:菜单->调试->添加配置{ "version": "0.2.0", "configurations": [ { "name": "Launch server.js via nodemon", "type": "node", "request": "launch", "runtimeExecutable": "nodemon", "program": "${workspaceRoot}/dist/app", "restart": true, "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ]}
配置完之后即可通过菜单->调试->启动调试或者快捷键来启动调试
问题三 hot-reload
nodemon的作用是一检测到文件修改就重启node server,不用再先终止进程再启动了。现在我们还差一步就是.ts文件一修改就重新编译
tsc -w //很简单
总结
每次开始编写程序前先执行tsc -w 然后F5开始调试,每次一修改ts文件就会重新编译和发布,在ts文件中也可以任意下断点
相关操作
> git clone https://github.com/pleerock/routing-controllers-koa-demo.git > cd routing-controllers-koa-demo > yarn install / npm install vscode>调试>添加配置 > tsc -w F5 (设置断点) 浏览器打开 http://localhost:3000/categories