Search code examples
typescriptexpressdebuggingvscode-debuggernodemon

Unable to use vscode debugger in a Express js with typscript project


Here is my package.json file

`

{
  "name": "crm-backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "concurrently \"yarn tsc --watch\" \"yarn tsc-alias --watch\" \"nodemon -q dist/index.js\""
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "mongoose": "^6.7.5"
  },
  "devDependencies": {
    "@types/express": "^4.17.14",
    "@types/mongoose": "^5.11.97",
    "@types/node": "^18.11.10",
    "concurrently": "^7.6.0",
    "nodemon": "^2.0.20",
    "tsc-alias": "^1.8.1",
    "typescript": "^4.9.3"
  }
}

`

I have tried many ways in launch.json

`

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Attach",
      "port": 1234,
      "request": "attach",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "type": "node"
    },
    {
      "name": "Launch Chrome with Debugger",
      "port": 7999,
      "request": "launch",
      "type": "chrome",
      "webRoot": "${workspaceFolder}/static",
    },
    {
      "name": "Nodemon: Attach Express.js + TypeScript 2",
      "type": "node",
      "request": "attach",
      "port": 9229,
      "restart": true,
      "protocol": "inspector",
      "cwd": "${workspaceFolder}/backend"
    }
  ]
}

`

Only "Nodemon: Attach Express.js + TypeScript" was working (for this i have to add "--inspect-brk=0.0.0.0:9229" in package.json after where nodemon writter), but it is catching breakpoint of output compiled "js" files not source "ts" files. (and i have to add.


Solution

  • Just add this to your tsconfig file:

    "compilerOptions": {
        "sourceMap": true
    }
    

    It will map compiled javascript back to typescript for debugging purposes, but don't forget to turn it off (maybe having tsconfig.prod file) when you will build your production bundle, because source maps will increase your bundle size