Hướng dẫn debug app NestJs

,

・Published on:

App NestJs trong Docker

Config project

  • Config tsconfig.json, bạn cần bổ sung thêm dòng sau để file ts biên dịch thành file js có source map
{ 
    "compilerOptions": { 
        "inlineSourceMap": true, 
    } 
}

Config docker

  • Docker cho app Nestjs bạn không phải config nhiều. Đối với app nestjs chỉ cần sửa lại script yarn start:debug trong package.json để chạy ở chế độ debug là được.
// nest start --debug 0.0.0.0:9229 --watch 
yarn start:debug
  • Expose cổng 9229 ra ngoài host.
ports:
    - 9229:9229

Config IDE

  • Lúc này IDE sẽ đóng vai trò giống như người xem, nó sẽ attach vào service theo port 9229 để dừng ở đúng breakpoint.
  • Đối với file .vscode/launch.json thì config như sau:
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to NestJS in Docker",
            "address": "localhost",
            "port": 9229,
            "restart": true,
            "protocol": "inspector",
            "localRoot": "${workspaceFolder}",
            "remoteRoot": "/app",
            "sourceMaps": true,
            "skipFiles": [
                "<node_internals>/**"
            ]
        }
    ]
}
  • port trùng với port trong lệnh yarn start:debug, thông thường là cổng 9229.
  • localRoot là folder chứa source code, đường dẫn đến root project của bạn.
  • remoteRoot là folder chứa source code trong docker, folder này thường được ánh xạ từ ngoài host vào trong docker.