Visual Studio Code (VSCode) is a powerful editor that supports a wide range of programming languages, including TypeScript. To debug TypeScript files in VSCode, follow these steps:
1. Install Necessary Plugins
First, ensure that TypeScript language support is installed in your VSCode. Typically, this can be achieved by installing the official extension named "TypeScript and JavaScript Language Features". Additionally, for a better debugging experience, I recommend installing the Debugger for Chrome or Debugger for Firefox extensions. If targeting a Node.js environment, install the Node.js Extension Pack.
2. Configure tsconfig.json File
Ensure that your TypeScript project has a correctly configured tsconfig.json file. This file specifies how the TypeScript compiler processes TypeScript files. Ensure that the "sourceMap" option is set to true, so that the compiled JavaScript files generate source maps, allowing the debugger to link to the original TypeScript source code.
For example, your tsconfig.json might look like this:
json{ "compilerOptions": { "target": "es6", "module": "commonjs", "sourceMap": true }, "include": ["src/**/*"] }
3. Configure VSCode Debugging Settings
In VSCode, open the Debug view (using Ctrl+Shift+D shortcut). Click "Create launch.json file" (usually at the top of the Debug sidebar), and select the environment, which could be Node.js or Chrome, depending on your project type.
In the generated launch.json file, you can configure specific debugging settings. Here is an example configuration for Node.js:
json{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/src/index.ts", "preLaunchTask": "tsc: build - tsconfig.json", "outFiles": ["${workspaceFolder}/dist/**/*.js"] } ] }
This configuration instructs VSCode to execute the TypeScript compilation task (preLaunchTask) before launching the program and to debug the compiled JavaScript files.
4. Start Debugging
Once all settings are configured, you can set breakpoints in your TypeScript files and start debugging by selecting the configured debugging session from the Debug view and clicking the green run button.
Real-World Example
For example, in a previous project, we developed a Node.js backend service using VSCode. During debugging, with the above settings, we could set breakpoints directly in the TypeScript source code and step through the program to inspect runtime states and variable values. This greatly simplified the debugging process and helped us quickly identify several key logical errors.