我想使用 Visual Studio 通过 Typescript 开发 Node.js 应用程序,并且只想要任何现代 IDE 的正常调试行为:调试代码、设置断点、查看变量等。遵循 official documentation guide ,运行任务时出现错误:Npm 任务 typescript 没有为以下配置提供任务
。
因此,我在tasks.json 文件中调用自定义npm 脚本:
启动.json
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach",
"port": 9229,
"preLaunchTask": "typescript"
}
]
任务.json
"tasks": [
{
"type": "shell",
"label": "typescript",
"command": "cd server; npm run build:live"
},
]
package.json
"scripts": {
"build:live": "nodemon --inspect --exec ./node_modules/.bin/ts-node -- ./index.ts"
}
现在应用程序正在编译并启动(也可以实时重新加载)。但没有调试工作,没有到达断点。在 VS Code 中调试 Typescript 真的那么难吗?
我正在使用最新的
最佳答案
在 VS Code 中进行 Typescript 的实时调试似乎很痛苦。我只能以与完整 Visual Studio 类似的方式进行常规调试:
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/index.ts",
"outFiles": [
"${workspaceRoot}/dist/**/*.js"
],
"sourceMaps": true,
"stopOnEntry": false,
"cwd": "${workspaceRoot}",
"env": {
"NODE_ENV": "development"
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnFirstSessionStart",
"preLaunchTask": "compile",
"name": "DEBUG"
}
]
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "compile",
"type": "typescript",
"tsconfig": "tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
请注意,您必须在 tsconfig.json
中设置 "sourceMap": "true"
。如果没有,则会出现找不到相应源映射的错误。这是因为 NodeJS 无法编译 TS。编译是由之前的 TypeScript 编译器 tsc 完成的。为了调试目的(例如到达断点),源映射可以将编译后的 js 映射到此处的 ts 源文件。
关于node.js - 调试在 Visual Studio Code 1.19.3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48523027/