TypeScript

Debugging

Introduction#

There are two ways of running and debugging TypeScript:

Transpile to JavaScript, run in node and use mappings to link back to the TypeScript source files

or

Run TypeScript directly using ts-node

This article describes both ways using Visual Studio Code and WebStorm. All examples presume that your main file is index.ts.

JavaScript with SourceMaps in Visual Studio Code

In the tsconfig.json set

"sourceMap": true,

to generate mappings alongside with js-files from the TypeScript sources using the tsc command.
The launch.json file:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}\\index.js",
            "cwd": "${workspaceRoot}",
            "outFiles": [],
            "sourceMaps": true
        }
    ]
}

This starts node with the generated index.js (if your main file is index.ts) file and the debugger in Visual Studio Code which halts on breakpoints and resolves variable values within your TypeScript code.

JavaScript with SourceMaps in WebStorm

Create a Node.js debug configuration and use index.js as Node parameters.

enter image description here

TypeScript with ts-node in Visual Studio Code

Add ts-node to your TypeScript project:

npm i ts-node

Add a script to your package.json:

"start:debug": "ts-node --inspect=5858 --debug-brk --ignore false index.ts"

The launch.json needs to be configured to use the node2 type and start npm running the start:debug script:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node2",
            "request": "launch",
            "name": "Launch Program",
            "runtimeExecutable": "npm",
            "windows": {
                "runtimeExecutable": "npm.cmd"
            },
            "runtimeArgs": [
                "run-script",
                "start:debug"
            ],
            "cwd": "${workspaceRoot}/server",
            "outFiles": [],
            "port": 5858,
            "sourceMaps": true
        }
    ]
}

TypeScript with ts-node in WebStorm

Add this script to your package.json:

"start:idea": "ts-node %NODE_DEBUG_OPTION% --ignore false index.ts",

Right click on the script and select Create ‘test:idea’… and confirm with ‘OK’ to create the debug configuration:

enter image description here

Start the debugger using this configuration:

enter image description here


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow