Debug a typescript node.js app in vscode
last updated: May 26, 2022
The VSCode debugger is a great tool that allows us to add breakpoints in our code and step through a process.
Attach
Attaching allows us to debug an app or process that is already running.
Run our node.js with the following command:
node_modules/.bin/ts-node-dev --inspect -- src/index.ts
We can then attach our debugger to our running process with the following configuration:
.vscode/launch.json
"version": "0.2.0",
"configurations": [
{
"name": "ts-node - Attach",
"port": 9229,
"request": "attach",
"cwd": "${workspaceRoot}",
"sourceMaps": true,
"skipFiles": ["<node_internals>/**"],
"type": "node"
}
]
}
Launch & Debug
Launching from the debugger allows us to start our app in debug mode
.vscode/launch.json
"version": "0.2.0",
"configurations": [
{
"name": "ts-node - Launch & Debug",
"type": "node",
"request": "launch",
"runtimeArgs": ["-r", "ts-node/register"],
"runtimeExecutable": "node",
"args": ["--inspect", "${workspaceFolder}/src/index.ts"],
"cwd": "${workspaceRoot}",
"skipFiles": ["<node_internals>/**", "node_modules/**"]
}
]
}
Docker
Setup our docker-compose.yml file to run our app in debug mode.
docker-compose.yml
version: "3.9"
services:
ts-node:
image: node:16-slim
working_dir: /usr/src/app
command: node -r ts-node/register --inspect=0.0.0.0:9229 src/index.ts
volumes:
- ./:/usr/src/app
ports:
- 3000:3000 # port exposed for node.js app
- 9229:9229 # port exposed for debugger
The main points to note are:
--inspect=0.0.0.0:9229
will allow us to debug our app in vscode9229:9229
expose our debugger port to the host machine so that vscode can attach to it
Attach our debugger to our running Docker container with the following configuration:
.vscode/launch.json
"version": "0.2.0",
"configurations": [
{
"name": "ts-node & Docker - Attach",
"port": 9229,
"request": "attach",
"cwd": "${workspaceRoot}",
"localRoot": "${workspaceFolder}",
"remoteRoot": "/usr/src/app",
"sourceMaps": true,
"skipFiles": ["<node_internals>/**"],
"type": "node"
}
]
}