Nest 官方默认推荐使用CLI启动本地调试程序, 然而有时候我们希望在程序中打断点来更加直观地查看程序的运行情况.
因为Nest 的程序通常是 TypeScript , 我们需要在项目中安装依赖来直接运行源码:
npm install --save-dev ts-node ts-node-dev
- ts-node:
ts-node
是一个在运行时将 TypeScript 代码编译为 JavaScript 的工具。 - ts-node-dev: 是在
ts-node
的基础上增加了热重载(hot-reloading)功能的工具.
在项目中新建 .vscode/launch.json
文件:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug NestJS",
"runtimeArgs": ["-r", "ts-node/register"],
"args": ["${workspaceFolder}/src/main.ts"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"env": {
"NODE_ENV": "development"
},
"restart": true,
"sourceMaps": true
}
]
}
“args” 指定了项目的启动文件main.ts 的位置;
以及, “env” 设置命令行变量 NODE_ENV=development;
因为我们需要程序修改了源码以后自动重启, 所以设置 “restart”: true
最后, 在VSCode中按F5, 可见程序进入断点停止, 并且能够显示数据结构和调用栈: