Debug with Nodemon and Typescript - Source
When we have our node project in typescript and want to debug we can use VSCode debugger. However we are not willing to sacrifice restarting the server on save or working directly in typescript. How can we achieve that?
The first step is to install our dev-dependencies. We are going to need:
- typescript
- ts-node
- nodemon
- @types/node
Install them like this: yarn add -D typescript ts-node nodemon @types/node
Then we can configure nodemon to work with ts-node creating a nodemon.json
file with this content.
{
"restartable": "rs",
"ignore": [".git", "node_modules/", "dist/", "coverage/"],
"watch": ["src/"],
"execMap": {
"ts": "node -r ts-node/register"
},
"env": {
"NODE_ENV": "development"
},
"ext": "js,json,ts"
}
Let’s go over the configuration:
- restartable — a command we can use to restart the program manually
- ignore — list of files we don’t want to trigger a program restart when changing
- watch — list of paths we do want to trigger a program restart when changing
- execMap — a mapping between a file type/extension to a runtime
- env — environment variables to include
- ext — the file extensions Nodemon monitores
In order to run it we must add these both scripts in our package.json:
"scripts": {
"dev": "nodemon --config nodemon.json src/index.ts",
"dev:debug": "nodemon --config nodemon.json --inspect-brk src/index.ts"
}
The difference between --inspect
and --inspect-brk
is that the later halts the execution when the program meets a breakpoint.
Now, in order to debug from VSCode we create a .vscode/launch.json
file with the following contents:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach",
"restart": true,
"processId": "${command:PickProcess}"
}
]
}
Then we run yarn dev:debug
and the program halts until we attach to it. From now on, it should stop on each breakpoint.