Skip to content

Instantly share code, notes, and snippets.

@ezequieltejada
Last active October 1, 2022 21:25
Show Gist options
  • Save ezequieltejada/0c5a0be191bff04d00d4f2f9b5147849 to your computer and use it in GitHub Desktop.
Save ezequieltejada/0c5a0be191bff04d00d4f2f9b5147849 to your computer and use it in GitHub Desktop.
Nodemon & Typescript

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?

Install dependencies

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

Configure nodemon

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

Run it

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.

Debugging in VSCode

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment