简体   繁体   English

Visual Studio Code - 通过 TypeScript 调试 Node JS

[英]Visual Studio Code - Debug Node JS through TypeScript

I'm currently trying to debug a Node JS application written in TypeScript from Visual Studio Code but I have some issues.我目前正在尝试从 Visual Studio Code 调试用 TypeScript 编写的 Node JS 应用程序,但我遇到了一些问题。 I have a situation similar to the one described on this question我的情况类似于此问题中描述的情况

|-- .settings
|----- launch.json
|-- bin
|----- app.js
|----- app.js.map
|--src
|----- app.ts
|-- tsconfig.json

Then I have the tsconfig.json file:然后我有tsconfig.json文件:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "outDir": "bin",
        "rootDir": "src",
        "sourceMap": true
    }
}

The app.ts : app.ts

console.log("Hello World!");

The launch.json :启动.json

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch type",
            "type": "node",
            "program": "src/app.ts",
            "stopOnEntry": false,
            "sourceMaps": true,
            "outDir": "bin"
        }
    ]
}

Then I manually compile the project from the command line with然后我从命令行手动编译项目

tsc

so I get two files in the bin directory.所以我在bin目录中得到了两个文件。 I set a breakpoint on app.ts and finally run the solution with F5 , the application starts and stops at the right line but on the JS file instead the TS one: why???我在app.ts上设置了一个断点,最后使用F5运行解决方案,应用程序在正确的行启动和停止,但在JS文件而不是TS文件上:为什么???

Am I doing something wrong or trying to achieve the impossible?我是在做错事还是试图实现不可能的目标?

Thank you very much for your help!非常感谢您的帮助! :) :)

EDIT编辑

I've just shared my project on GitHub in order to make things easier!我刚刚在GitHub 上分享了我的项目,以使事情变得更容易! Take a look if you can!可以的话就看看吧! :) :)

It is absolutely possible.这是绝对可能的。

The most likely reason is that the node.js cannot locate corresponding ts files using generated map.js file.最可能的原因是 node.js 使用生成的 map.js 文件找不到对应的 ts 文件。 You can try to specify "sourceRoot" in tsconfig.json to point to the root of your project:您可以尝试在 tsconfig.json 中指定“sourceRoot”以指向项目的根目录:

sourceRoot: "/Users/SomeUser/projects/test"

Personally I prefer to use gulp for this purpose and in my case it would look like this (note - I do not hardcore sourceRoot path here by using node.js global variable '__dirname'):就我个人而言,我更喜欢为此目的使用 gulp,在我的情况下,它看起来像这样(注意 - 我在这里没有通过使用 node.js 全局变量 '__dirname' 来硬核 sourceRoot 路径):

var ts = require('gulp-typescript');

gulp.task('build.js.dev', function() 
{
    var tsProject = ts.createProject('tsconfig.json');

    var tsResult = tsProject.src()
        .pipe(sourcemaps.init())   
        .pipe(ts(tsProject));  

    return merge([
        //Write definitions 
        //tsResult.dts.pipe(gulp.dest("bin")),
        //Write compiled js
        tsResult.js.pipe(sourcemaps.write("./", { sourceRoot: __dirname })).pipe(gulp.dest("bin"))]);
});

After that examine the generated map.js file.之后检查生成的 map.js 文件。 It should contain something like this lines in the beginning:它应该在开头包含类似这样的内容:

"sources":["src/app.ts"]

and in the end:最后:

"sourceRoot":"/Users/SomeUser/projects/test"

When combined together they must point to the valid location of your app.ts file.组合在一起时,它们必须指向 app.ts 文件的有效位置。 If not - adjust sourceRoot correspondingly.如果不是 - 相应地调整 sourceRoot。

[EDIT] [编辑]

Below are the parts of the project identical to yours (without gulp) - that I can debug on my machine.以下是与您的项目相同的项目部分(没有 gulp) - 我可以在我的机器上进行调试。

launch.json:启动.json:

{
    // Name of configuration; appears in the launch configuration drop down menu.
    "name": "Launch Server",
    // Type of configuration.
    "type": "node",
    // Workspace relative or absolute path to the program.
    "program": "${workspaceRoot}/src/app.ts",
    // Automatically stop program after launch.
    "stopOnEntry": false,
    // Command line arguments passed to the program.
    "args": [],
    // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
    "cwd": "${workspaceRoot}",
    // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
    "runtimeExecutable": null,
    // Optional arguments passed to the runtime executable.
    "runtimeArgs": ["--nolazy"],
    // Environment variables passed to the program.
    "env": {
        "NODE_ENV": "development"
    },
    // Use JavaScript source maps (if they exist).
    "sourceMaps": true,
    // If JavaScript source maps are enabled, the generated code is expected in this directory.
    "outDir": "${workspaceRoot}/bin",
    "request": "launch"
}

tsconfig.json: tsconfig.json:

{ 
    "compilerOptions": { 
        "emitDecoratorMetadata": true, 
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "module": "commonjs", 
        "target": "es6",
        "sourceMap": true,
        "outDir": "bin",
        "declaration": true,
        "noImplicitAny": true
    },
    "exclude": [
        "node_modules",
        "bin",
        ".vscode",
        "typings/browser.d.ts",
        "typings/browser/**"
    ]
} 

And build task in tasks.json:并在 tasks.json 中构建任务:

{
    "version": "0.1.0",

    // The command is tsc. Assumes that tsc has been installed locally using npm install typescript
    "command": "${workspaceRoot}/node_modules/typescript/bin/tsc",

    // The command is a shell script
    "isShellCommand": true,

    // Show the output window only if unrecognized errors occur.
    "showOutput": "silent",

    // args is the HelloWorld program to compile.
    "args": [],

    // use the standard tsc problem matcher to find compile problems
    // in the output.
    "problemMatcher": "$tsc"
}

[EDIT] [编辑]

I have done the following minor updates to your git repository to be able to debug it locally.我已经对您的 git 存储库进行了以下小更新,以便能够在本地调试它。

Add package.json in the root folder, and specify there tsc as dependency (I prefer local installations):在根文件夹中添加 package.json,并指定 tsc 作为依赖项(我更喜欢本地安装):

{
  "name": "123",
  "namelower": "123",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
  },
  "devDependencies": {
    "typescript": "latest"
  }
}

then go to your git "stackoverflow" root folder and run in command prompt:然后转到您的 git "stackoverflow" 根文件夹并在命令提示符下运行:

npm install

Change in tasks.json "command" line to:将 tasks.json “命令”行更改为:

"command": "${workspaceRoot}/node_modules/typescript/bin/tsc",

After doing these steps and building the project I was able to put a breakpoint in app.ts and VSCode stopped on it upon run (F5)完成这些步骤并构建项目后,我能够在 app.ts 中放置一个断点,并且 VSCode 在运行时停止(F5)

[UPDATE] [更新]

Version of tasks.json compatible with windows:与windows兼容的tasks.json版本:

{
    "version": "0.1.0",
    "command": "tsc",

    "showOutput": "always",

    "windows": {
        "command": "node.exe"
    },

    "args": ["${workspaceRoot}\\node_modules\\typescript\\bin\\tsc.js"],

    "problemMatcher": "$tsc"    
}

Hope this helps.希望这可以帮助。

Juli 2022 Nothing additional (like gulp etc.) is necessary 2022 年7 月不需要额外的东西(如 gulp 等)

Step 1:步骤1:

Simply install ts-node globally:只需全局安装ts-node

npm i -g ts-node

Step 2:第2步:

Add a new configuration in launch.json (VSCode).在 launch.json (VSCode) 中添加新配置。 The following is for macOS;以下是针对 macOS 的; for other operating systems, modify the runtimeExecutable property accordingly:对于其他操作系统,相应地修改runtimeExecutable属性:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "TypeScript Debugging",
      "type": "node",
      "request": "launch",
      "args": ["${relativeFile}"],
      "cwd": "${workspaceRoot}",
      "runtimeExecutable": "/opt/homebrew/bin/ts-node"
    }
  ]
}

Step 3:第 3 步:

Open the TypeScript file you want to debug and set a break point.打开要调试的 TypeScript 文件并设置断点。

Step 4:第4步:

and click left on "Rund and Debug."然后单击左侧的“运行和调试”。

VSCode 中的 TypeScript 调试

Backup: tsconfig.json备份: tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["ESNext", "DOM"],
    "module": "esnext",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipDefaultLibCheck": true,
    "skipLibCheck": true,
    "sourceMap": true
  }
}

This is how I am debugging my typescript (express) project.这就是我调试我的 typescript (express) 项目的方式。 Use ts-node you don't have to compile manually .使用 ts-node 你不必手动编译。 Using this configs i am directly debugging in my typescript files.使用这个配置我直接在我的打字稿文件中调试。 Hope this helps someone.希望这可以帮助某人。

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Current TS File",
      "type": "node",
      "request": "launch",
      "args": ["${workspaceRoot}/src/app.ts"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
    }
  ]
}

was having the same issue trying to figure out how to debug TS+nodejs with aws Lambda.在试图弄清楚如何使用 aws Lambda 调试 TS+nodejs 时遇到了同样的问题。 Looks like the ts-node-dev package is faster than nodemon in terms of watch TS file changes.看起来ts-node-dev包在监视TS 文件更改方面比nodemon快。

npm install ts-node-dev --save-dev npm install ts-node-dev --save-dev

finally add below config in launch.json :最后在launch.json中添加以下配置:

{
  "version": "1.0.0",
  "configurations": [
    {
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "name": "Local Server",
      "restart": true,
      "request": "launch",
      "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/ts-node-dev",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "type": "node",
      "runtimeArgs": [
        "--respawn"
      ],
      "args": [
        "${workspaceFolder}/src/script/local.server.ts"
      ]
    }
  ]
}
    

Press F5 should launch your local server either with native http or express/koa/hapi... etc. Now you can set break points in code.F5应该使用本机httpexpress/koa/hapi...等启动本地服务器。现在您可以在代码中设置断点。 Also the ts-node-dev will watch the TS file change and reload server on each save. ts-node-dev还将在每次保存时观察 TS 文件更改并重新加载服务器。

I wrapped up a small library for this if you happen to develop with aws lambda如果您碰巧使用aws lambda开发,我为此包装了一个小型库

https://github.com/vcfvct/ts-lambda-local-dev

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 visual studio code - 使用typescript调试配置的节点js错误 - visual studio code - node js error with typescript debug configuration 使用Visual Studio Code调试节点js - Debug node js with Visual Studio Code 通过Visual Studio 2017中的任务运行器资源管理器调试节点js - debug node js through task runner explorer in Visual Studio 2017 Visual Studio Code 中调试控制台中的 Node.js readline - Node.js readline in debug-console in Visual Studio Code 如何在 Visual Studio Code 中调试子 Node.JS 进程? - How to debug child Node.JS process in Visual Studio Code? Visual Studio 代码断点在使用 TypeScript 的 Node.js 上不起作用 - Visual Studio code breakpoint not working on Node.js using TypeScript Visual Studio Code 未绑定断点 Node JS React TypeScript - Visual Studio Code unbound breakpoint Node JS React TypeScript 如何使用Node JS Tools在Visual Studio中调试Yeoman生成器KO(带有typescript和gulp)Node JS项目 - How can I debug a Yeoman generator KO (with typescript and gulp) Node JS project in Visual studio with Node JS Tools for visual studio 无法在Visual Studio Code中调试TypeScript - Cant debug TypeScript in Visual Studio Code 在Visual Studio代码调试中表达Typescript Gulp - Express Typescript Gulp in Visual Studio Code Debug
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM