1

I would like to debug my typescript code (which runs in NodeJS) with VSCode. The following code is my starting point and works just fine.

Typescript code:

//src/index.ts
console.log('line 1');
console.log('line 2');

The compiler settings:

//tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "sourceMap": true
    },
    "exclude": [
        "node_modules"
    ]
}

And the launch configuration

//.vscode/launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}/src/index.js"
        }
    ]
}

In the above setup, I can add breakpoints in the typescript code and then start debugging.

All typescript source code is in a directory called src/. I would like to specify this in the compiler settings by adding the following config option:

"compilerOptions": {
    //...
    "sourceRoot": "src"

It still compiles just fine and when executed, it prints "line 1", "line 2".

However, the breakpoints no longer work. I looked at the generated sourcemaps and they specify a path "sourceRoot":"src". I guess that this breaks the sourcemap lookup. Since the original sources are in the same folder as the generated output. How do I configure this correctly in the compiler?

2 Answers 2

2

The easiest way I have found to debug ts in vscode is to use ts-node

Then I use ts-node in my launch script as so

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ts node inspector",
      "type": "node",
      "request": "launch",
      "args": ["${workspaceRoot}/src/server.ts"],
      "runtimeArgs": ["-r", "ts-node/register"],
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "internalConsoleOptions": "openOnSessionStart",
      "env": {
        "TS_NODE_IGNORE": "false"
      }
    }
  ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice, I didn't even know about ts-node.
2

The documentation explains that sourceRoot:

Specifies the location where debugger should locate TypeScript files instead of source locations. Use this flag if the sources will be located at run-time in a different location than that at design-time. The location specified will be embedded in the sourceMap to direct the debugger where the source files will be located.

So I have been using it incorrectly.

1 Comment

Oh wow, thank you. Sitting here for hours at the same problem. I had my index.ts in the src of the root. After I read your doc I putted the index in the root and kept additional src code in the src dir.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.