typescript 如何在 Visual Studio 代码中调试打字稿文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31169259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:42:38  来源:igfitidea点击:

how to debug typescript files in visual studio code

typescriptvisual-studio-code

提问by MonkeyBonkey

using version 0.3 of visual studio code and I'm not sure how to enable sourcemaps and debug the ts file

使用 0.3 版的 Visual Studio 代码,但我不确定如何启用源映射和调试 ts 文件

I get the following error can't launch program '/Projects/app-server/server.ts'; enabling source maps might help

我收到以下错误 can't launch program '/Projects/app-server/server.ts'; enabling source maps might help

how do I enable sourcemaps and typescript debugging. Sourcemap is set to true in my

如何启用源映射和打字稿调试。Sourcemap 在我的设置中设置为 true

tsconfig.json

配置文件

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "sourceMap": true
    }
}

launch.json

启动文件

{
    "version": "0.1.0",
    // List of configurations. Add new configurations or edit existing ones.  
    // ONLY "node" and "mono" are supported, change "type" to switch.
    "configurations": [
        {
            // Name of configuration; appears in the launch configuration drop down menu.
            "name": "Launch server.ts",
            // Type of configuration. Possible values: "node", "mono".
            "type": "node",
            // Workspace relative or absolute path to the program.
            "program": "server.ts",
            // Automatically stop program after launch.
            "stopOnEntry": true,
            // 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": ".",
            // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
            "runtimeExecutable": null,
            // Environment variables passed to the program.
            "env": { }
        }, 
        {
            "name": "Attach",
            "type": "node",
            // TCP/IP address. Default is "localhost".
            "address": "localhost",
            // Port to attach to.
            "port": 5858
        }
    ]
}

采纳答案by Manu

This configuration is working fine for me:

这个配置对我来说很好用:

Project distribution

项目分布

|-- .vscode
    |----- launch.json
|-- bin
    |----- app.js
    |----- app.js.map
|-- src
    |----- app.ts
|-- node_modules
    |-- [..]
|-- tsconfig.json
|-- [...]

The idea is compile the typescript under srcfolder and place it under binfolder.

这个想法是编译src文件夹下的打字稿并将其放在bin文件夹下。

tsconfig.json

配置文件

It's important to active sourceMapoption.

主动sourceMap选择很重要。

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

launch.json

启动文件

==== EDIT ====

==== 编辑 ====

This is the configuration I'm currently using at Visual Studio Code v1:

这是我目前在 Visual Studio Code v1 中使用的配置:

{
    "version": "0.2.0",
    "configurations": [
        {
            "args": [],
            "cwd": "${workspaceRoot}",
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "name": "DEBUG",
            "outDir": "${workspaceRoot}/bin",
            "preLaunchTask": "compile",
            "program": "${workspaceRoot}/src/app.ts",
            "request": "launch",
            "runtimeArgs": [
                "--nolazy"
            ],
            "runtimeExecutable": null,
            "sourceMaps": true,
            "stopOnEntry": false,
            "type": "node"
        },
        {
            "name": "Attach",
            "type": "node",
            "request": "attach",
            "port": 5858
        }
    ]
}

Note the key preLaunchTaskis extremely helpful if you're using any task runner as gulpbecause the IDE is able to detect its tasks by name.

请注意,preLaunchTask如果您将任何任务运行器用作gulp,该键非常有用,因为 IDE 能够按名称检测其任务。

Running

跑步

  1. Compile your ts(typing in a terminal rm -r bin/ ; tscor executing your compiling task)
  2. In visual Code play Launch type(our configuration name)
  3. Enjoy!
  1. 编译您的ts(在终端中输入rm -r bin/ ; tsc或执行您的编译任务)
  2. 在可视化代码播放中Launch type(我们的配置名称)
  3. 享受!

debuging

调试

回答by Grogi

I think it got simpler and simpler over the releases...

我认为它在发布后变得越来越简单......

I have installed ts-node(https://github.com/TypeStrong/ts-node), so my config files end up very simple.

我已经安装ts-nodehttps://github.com/TypeStrong/ts-node),所以我的配置文件最终非常简单。

launch.json

启动文件

{
        "name": "Launch index.ts",
        "type": "node",
        "request": "launch",
        "runtimeArgs": [
            "-r",
            "ts-node/register"
        ],
        "args": [
            "${workspaceFolder}/src/index.ts"
        ]
}

There are two things worth noting:

有两点值得注意:

  • runtimeArgs- passed to node to register the ts-node to handle the TypeScript files.
  • there is no programproperty. The name of TS file to start is given as first argument instead.
  • runtimeArgs- 传递给 node 以注册 ts-node 来处理 TypeScript 文件。
  • 没有program财产。要启动的 TS 文件的名称作为第一个参数给出。

That way you do not need to compile the TS to JS, you can even have modules written in TS not compiled to JS yet.

这样你就不需要将 TS 编译成 JS,你甚至可以将用 TS 编写的模块还没有编译成 JS。

回答by Aakash Malhotra

This is what has been working for me with latest TS and VsCode as of November,2017

这就是截至 2017 年 11 月的最新 TS 和 VsCode 对我有用的东西

Following configuration will help you start the server and debug TS inside VS Code

以下配置将帮助您启动服务器并在 VS Code 中调试 TS

This is what my tsconfig.jsonlooks like:

这是我的tsconfig.json 的样子:

{
    "compilerOptions": {
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": ["es2017", "dom"],
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "../build",
        "sourceMap": true,
        "target": "es2016",
        "typeRoots": [
            "../node_modules/@types"
        ]
    },
    "include": [
        "**/*.ts"
    ],
    "exclude": [
        "../node_modules",
        "../*.js"
    ]
}

And this is what my directory structurelooks like:

这就是我的目录结构的样子:

enter image description here

在此处输入图片说明

If you pay attention you would see my src folder and build folder(containing resultant transpiled JS and map files) lives side by side which really helps me maintain a logical directory structure.

如果您注意,您会看到我的 src 文件夹和 build 文件夹(包含生成的转译的 JS 和地图文件)并排存在,这确实有助于我维护逻辑目录结构。

Ok, now comes the launch config:

好的,现在是启动配置

{
            "type": "node",
            "request": "launch",
            "name": "Start and Debug",
            "preLaunchTask": "nb-tsc-watch",
            "timeout": 10000,
            "program": "${workspaceFolder}/backend/src/app.ts",
            "restart": true,
            "cwd": "${workspaceRoot}",
            "outFiles": [
                "${workspaceFolder}/backend//build/**/*.js"
            ],
            "sourceMaps": true
        }

You can use whatever preLaunchTask you want to use, or even skip it. If you skip it, you would have to transpile TS to JS manually.

您可以使用任何想要使用的 preLaunchTask,甚至可以跳过它。如果跳过它,则必须手动将 TS 转换为 JS。

This is what I do in my task nb-tsc-watch

这就是我在我的任务中所做的 nb-tsc-watch

{
            "label": "nb-tsc-watch",
            "type": "typescript",
            "tsconfig": "backend/src/tsconfig.json",
            "option": "watch",
            "problemMatcher": [
                "$tsc-watch"
            ]
        }

回答by code5

For the more later version of VSCode as of Feb/2017, this is what worked for me (it's a combination of what both @manu and @tommy Falgout have provide):

对于截至 2017 年 2 月的更高版本的 VSCode,这对我有用(这是@manu 和 @tommy Falgout 提供的组合):

It assumes that your json out files are in a destfolder and your source in a srcfolder, respectively

它假设您的 json 输出文件分别位于dest文件夹中,而您的源文件位于src文件夹中

/.vscode/launch.json

/.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [{
            "type": "node",
            "request": "launch",
            "name": "Launch",
            "sourceMaps": true,
            "stopOnEntry": true,
            "console": "internalConsole",
            "cwd": "${workspaceRoot}",
            "program": "${workspaceRoot}/src/main.ts",
            "outFiles": ["${workspaceRoot}/dest/*.js"]
        },
        {
            "type": "node",
            "request": "attach",
            "name": "Attach to Process",
            "port": 5858,
            "outFiles": []
        }
    ]
}

tsconfig.json

配置文件

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "module": "commonjs",
        "outDir": "dest",
        "rootDir": "src"
    },
    "exclude": [
        "node_modules"
    ]
}

回答by mummybot

The below setup tests mocha chai with breakpoints. It works by transpiling src to lib directory and then running tests in lib with sourceMapping back to src.

下面的设置使用断点测试 mocha chai。它的工作原理是将 src 转换为 lib 目录,然后在 lib 中使用 sourceMapping 运行测试返回 src。

.vscode/launch.json

.vscode/launch.json

{
    "type": "node",
    "request": "launch",
    "preLaunchTask": "tsc",
    "name": "Run Mocha",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "args": ["lib/**/*.js"],
    "cwd": "${workspaceRoot}",
    "sourceMaps": true,
    "outFiles": ["${workspaceRoot}/lib/**/*.js"]
}

tsconfig.json

配置文件

{
  "compilerOptions": {
      "module": "commonjs",
      "sourceMap": true,
      "outDir": "lib",
      "target": "es6"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

.vscode/tasks.json

.vscode/tasks.json

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "args": ["-p", "."],
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}

package.jsonto show installed modules. Scripts are irrelevant to debugging.

package.json显示已安装的模块。脚本与调试无关。

"scripts": {
  "test": "mocha --compilers ts:ts-node/register src/**/*.spec.ts",
  "test:coverage": "nyc -e '.ts' npm test"
},
"dependencies": {
  "@types/chai": "^3.4.35",
  "@types/mocha": "^2.2.39",
  "@types/node": "^7.0.5",
  "@types/sinon": "^1.16.35",
  "chai": "^3.5.0",
  "mocha": "^3.2.0",
  "nyc": "^10.1.2",
  "sinon": "^1.17.7",
  "ts-node": "^2.1.0",
  "typescript": "^2.2.1"
}
  • Mac OSX 10.12.3 Sierra
  • Visual Studio Code 1.10.1
  • NodeJS v7.7.1
  • Mac OSX 10.12.3 塞拉利昂
  • 可视化工作室代码 1.10.1
  • NodeJS v7.7.1

回答by Tommy Falgout

The answer by @manu pointed me in the right direction; however, with the latest version of VSCode, I still had the same problem. This is the fix that worked for me:

@manu 的回答为我指明了正确的方向;但是,使用最新版本的 VSCode,我仍然遇到同样的问题。这是对我有用的修复:

https://github.com/Microsoft/vscode/issues/13499

https://github.com/Microsoft/vscode/issues/13499

"outFiles": [ "${workspaceRoot}/js/*.js" ]

回答by Bruce Lee

2017/12/17
.vscode/launch.json```json

2017/12/17
.vscode/launch.json```json

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/src/index.ts",
      "outFiles": [
        "${workspaceRoot}/dist/index.js"
      ],
      "sourceMaps": true,
      "stopOnEntry": false,
      "args": [],
      "cwd": "${workspaceRoot}",
      "env": {
          "NODE_ENV": "development"
      },
      "console": "internalConsole",
      "preLaunchTask": "compile",
      "name": "DEBUG"
    },
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to Process",
      "port": 5858
    }
  ]
}

.vscode/tasks.json

.vscode/tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "compile",
      "type": "typescript",
      "tsconfig": "tsconfig.json",
      "problemMatcher": [
          "$tsc"
      ],
      "group": {
          "kind": "build",
          "isDefault": true
      }
    }
  ]
}

tsconfig.json

配置文件

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "target": "es5",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": [
    "**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

回答by ford04

Auto-configuration approaches

自动配置方法

A simple, automatic config is sufficient for many use cases - no need to configure launch.jsonmanually. Prerequisite: Enable sourcemapsin workspace tsconfig.json:

对于许多用例来说,一个简单的自动配置就足够了 - 无需launch.json手动配置。先决条件:在工作区中启用源映射tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    // ...
  }
}

1.) Debug current file without launch.json

1.)调试当前文件而不launch.json

Just open or re-focus the file and then press F5(Start Debugging). If multiple debug environments exist like Chrome and Node.js, select the latter.

只需打开或重新聚焦文件,然后按F5(开始调试)。如果存在多个调试环境,如 Chrome 和 Node.js,则选择后者。

Note: This currently requires no other entry to be present in launch.json. Next VS Code release will come with single file debug improvements.

注意:这目前不需要其他条目存在于launch.json. 下一个 VS Code 版本将带有单文件调试改进

2.) Auto Create launch.json

2.) 自动创建 launch.json

Go to Debug view (CtrlShiftD) and click "create a launch.json file". This will create a debug entry for the mainfield file of package.jsonor the active file, if no mainexists. Example:

转到调试视图 ( CtrlShiftD) 并单击“创建 launch.json 文件”。如果不存在,这将为main字段文件package.json或活动文件创建一个调试条目main。例子:

  "configurations": [ // auto-generated 
    { 
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}\dist\A.js",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": [
        "${workspaceFolder}/dist/**/*.js"
      ]
    }
  ]

Note: This requires launch.jsonto not be present before.

注意:这要求launch.json之前不存在。

3.) Attach debugger to running program

3.) 将调试器附加到正在运行的程序

Turn on Auto Attach featurein settings.jsonor via UI → "Debug: Toggle Auto Attach".

在UI中或通过 UI打开自动附加功能settings.json→“调试:切换自动附加”。

"debug.node.autoAttach": "on" // in settings.json

Start the node program in debug mode. Shortly after, VS Code will start debugging.

在调试模式下启动节点程序。不久之后,VS Code 将开始调试。

node --inspect-brk dist/A.js

Or use "Debug: Attach to Node Process"(also with launch.json: "${command:PickProcess}").

或者使用“调试:附加到节点进程”(也使用launch.json: "${command:PickProcess}")。

回答by Tom

If you do not want to hardcode filenames but like simple Grogi'sversion here ? Using info from VS variable reference pageyou can do 2 things:

如果您不想硬编码文件名但喜欢简单的Grogi版本?使用来自VS 变量参考页面的信息,您可以做两件事:

npm i ts-node

then launch.jsonlike (full in case, but you can grab only this one configurations from):

然后launch.json之类的(以防万一,但您只能从中获取这一配置):

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch TS",
            "type": "node",
            "request": "launch",
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}/${fileBasename}"
            ]
        }
    ]
}

Few examples from that VSC page - sometimes somewhere you can use Ctrl+Space to get them, but does not work inside existing for me:

该 VSC 页面中的几个示例 - 有时您可以在某个地方使用 Ctrl+Space 来获取它们,但在我现有的内部不起作用:

${workspaceFolder} - /home/your-username/your-project
${workspaceFolderBasename} - your-project
${file} - /home/your-username/your-project/folder/file.ext
${relativeFile} - folder/file.ext
${relativeFileDirname} - folder
${fileBasename} - file.ext
${fileBasenameNoExtension} - file
${fileDirname} - /home/your-username/your-project/folder
${fileExtname} - .ext
${lineNumber} - line number of the cursor
${selectedText} - text selected in your code editor
${execPath} - location of Code.exe

回答by fredtma

For me, after so many launch.json configs. I came to find that using jestJswith istanbulcause my breakpoint not to break at the correct location until I set the config to:

对我来说,经过这么多的 launch.json 配置。我发现在伊斯坦布尔使用jestJs会导致我的断点不会在正确的位置中断,直到我将配置设置为:

config.collectCoverage = false;

config.collectCoverage = false;

See issue

查看问题