Search code examples
node.jstypescript

Can't debug typescript nodejs application in vs-code


I'm trying to debug my typescript express application with vs-code debugger, it works fine with node 16 but throw an error Unknown file extension .ts when i upgraded my project like node to 20 lts and commonjs to esm.

So far i've node 20.11.1, ts-node 10.9.2 and nodemon 3.0.1

This is my vs-code launch.json

{
    "type": "node",
    "request": "launch",
    "name": "Typescritpt node",
    "skipFiles": [
        "<node_internals>/**"
    ],
    "runtimeExecutable": "nodemon",
    "internalConsoleOptions": "neverOpen",
    "console": "integratedTerminal",
    "program": "${file}",
}

I've tried using --esm flag but it doesn't helped me.


Solution

  • You cannot use ts-node-esm or --esm anymore with node 20.11.1 and ts-node 10.9.2 because there are so many incompatibility between them.

    When i've face this is error, i decided to use tsx instead of ts-node which is seamlessly support for both commonjs and ESModule

    1. Install tsx globally

      npm install -g tsx
      
    2. Create nodemon.json since ts-node is default compiler we have to change that to tsx

       {
           "execMap": {
               "ts": "tsx"
           }
       }
      
    3. Add this to package.json

       "scripts": {
         "dev": "nodemon index.ts"
       }
      
    4. Finally configure launch.json

      {
           "type": "node",
           "request": "attach",
           "name": "Attach process",
           "processId": "${command:PickProcess}",
           "restart": true,
       }
      

    Start the debug server using new command npm run dev and choose the process to attach vs-code debugger