How to debug TypeScript code in VS Code



Image not found!!

Debugging TypeScript code in Visual Studio Code (VS Code) is a straightforward process, and it can be done using the built-in debugging capabilities. Here's a step-by-step guide:

  1. Install TypeScript: Ensure that TypeScript is installed globally on your machine. You can install it using the following command:

    bash
    npm install -g typescript
  2. Initialize tsconfig.json: If you don't already have a tsconfig.json file in your project, you can generate one using the following command:

    bash
    tsc --init

    This command creates a basic tsconfig.json file. Make sure to configure it according to your project's needs.

  3. Install Required Packages: Make sure you have ts-node and source-map-support installed as development dependencies. You can install them using:

    bash
    npm install --save-dev ts-node source-map-support
  4. Update tsconfig.json for Source Maps: In your tsconfig.json file, make sure you have the following settings to generate source maps:

    json
    { "compilerOptions": { "sourceMap": true // ... other options } }
  5. Configure Launch Configuration: In your VS Code project, create a launch.json file in the .vscode directory (if it doesn't already exist) and configure it for TypeScript debugging. Add a configuration similar to the following:

    json
    { "version": "0.2.0", "configurations": [ { "name": "Debug TypeScript", "type": "node", "request": "launch", "program": "${workspaceFolder}/node_modules/ts-node/dist/bin.js", "args": ["${workspaceFolder}/path/to/your/ts-file.ts"], "runtimeArgs": ["-r", "source-map-support/register"], "sourceMaps": true, "cwd": "${workspaceFolder}", "protocol": "inspector", "console": "integratedTerminal" } ] }

    Make sure to replace "${workspaceFolder}/path/to/your/ts-file.ts" with the actual path to your TypeScript file.

  6. Set Breakpoints: Place breakpoints in your TypeScript code by clicking on the left margin of the editor or using the F9 key.

  7. Start Debugging: Press F5 or use the "Run and Debug" panel to start debugging. VS Code will launch the debugger, and you can interact with it using the debugger panel.

That's it! You should now be able to debug your TypeScript code in Visual Studio Code. The debugger will stop at breakpoints, and you can inspect variables, step through the code, and use other debugging features.