如何在visual studio代码中调试typescript文件

时间:2015-07-01 18:44:59

标签: typescript visual-studio-code

使用Visual Studio代码的0.3版,我不知道如何启用源图并调试ts文件

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

如何启用源映射和打字稿调试。我的

中的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
        }
    ]
}

12 个答案:

答案 0 :(得分:47)

此配置对我来说很好:

项目分发

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

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

tsconfig.json

激活sourceMap选项很重要。

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

launch.json

====编辑====

这是我目前在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
        }
    ]
}

注意,如果您将任务运行器用作gulp,则键{{1​​}}非常有用,因为IDE可以按名称检测其任务。

运行

  1. 编译您的preLaunchTask(输入终端ts或执行编译任务)
  2. 在可视代码播放rm -r bin/ ; tsc(我们的配置名称)
  3. 享受!
  4. debuging

答案 1 :(得分:18)

我认为它在发行版中变得越来越简单...

我已经安装了ts-node,所以我的配置文件最终变得非常简单...

launch.json

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

有两点值得注意:

  • runtimeArgs-传递给节点以注册ts节点以处理TypeScript文件。
  • 没有program属性。将要启动的TS文件的名称改为第一个参数。

这样一来,您无需将TS编译为JS,甚至可以使用TS编写的模块尚未编译为JS。

答案 2 :(得分:12)

截至2017年11月,这是最新的TS和VsCode一直在为我工作

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

这就是我的 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"
    ]
}

这就是我的目录结构

enter image description here

如果你注意你会看到我的src文件夹和构建文件夹(包含结果已转换的JS和地图文件)并存,这真的有助于我维护一个逻辑目录结构。

好的,现在是启动配置

{
            "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
        }

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

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

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

答案 3 :(得分:7)

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

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

<强> /。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"
    ]
}

答案 4 :(得分:7)

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

<强> .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

{
    // 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.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

答案 5 :(得分:3)

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

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

&#13;
&#13;
"outFiles": [ "${workspaceRoot}/js/*.js" ]
&#13;
&#13;
&#13;

答案 6 :(得分:3)

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

{
  // 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"
  ]
}

答案 7 :(得分:1)

自动配置方法

简单,自动的配置足以满足许多使用情况-无需手动配置launch.json。先决条件:在工作区tsconfig.json中启用sourcemaps

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

1。)调试当前文件without launch.json

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

注意:目前,launch.json中不需要其他条目。下一个VS Code版本将随附single file debug improvements

2。)自动创建launch.json

转到调试视图( Ctrl Shift D ),然后单击“创建launch.json文件”。如果不存在main,这将为package.json的{​​{1}}字段文件或活动文件创建调试条目。示例:

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" ] } ] 之前不能出现。

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

launch.json中或通过用户界面→“调试:切换自动附加”打开Auto Attach feature

settings.json

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

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

或使用"Debug: Attach to Node Process"(也与node --inspect-brk dist/A.js launch.json一起使用)。

答案 8 :(得分:0)

我刚刚编写了自己的PowerShell函数作为preLaunchTask。这可能是比以前更糟的解决方案,但可以在preLaunchTask字段下添加更多灵活性来注入更多任务。因为目前它不支持数组,并且只允许在启动操作之前运行一个任务。

<强> launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Node.js",
            "program": "${file}",
            "preLaunchTask": "RebuildTypeScript",
            "outFiles": [
                "${workspaceRoot}/js/**/*.js"
            ]
        }
    ]
}

<强> tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "typescript",
            "tsconfig": "tsconfig.json",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },        
        {
            "taskName": "RebuildTypeScript",
            "type": "shell",
            "command": "Powershell ./RebuildTypeScript.ps1",
            "group": "none",
            "presentation": {
                "reveal": "never"
            }
        }       
    ]
}

<强> RebuildTypeScript.ps1

$currentDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
function CompileTypeScriptFiles($folder) {
    $tsFiles = Get-ChildItem $folder -Filter "*.ts" -Recurse
    $tsFiles | ForEach-Object {
        $tsFile = $_.FullName;
        $options = $tsFile + " --outDir js --sourceMap"
        Start-Process "tsc" $options 
    }
}


CompileTypeScriptFiles $currentDir

答案 9 :(得分:0)

对我来说,经过了那么多的launch.json配置。我发现在 istanbul 中使用 jestJs 会导致我的断点不会在正确的位置中断,除非将配置设置为:

config.collectCoverage = false;

请参见issue

答案 10 :(得分:0)

如果您是从命令行运行脚本的,则在最新的Visual Studio Code版本中,可以跳过创建launch.json的工作,这有时是一项艰巨的任务。相反,您可以将调试器自动附加到从命令行运行的任何ts-nodenode命令中。

  1. tsconfig.json启用源映射-TypeScript配置需要源映射支持,否则无法进行调试。
{
  "compilerOptions": {
    "sourceMap": true
  },
}
  1. 在Visual Studio代码调试器上启用自动附加。这是任务栏上的按钮,但也可以通过命令面板访问。

auto attach

  1. 代替以以下方式启动脚本:
ts-node myscript.ts

启动为

node -r ts-node/register --inspect-brk myscript.ts

您将在Node启动时看到它:

Debugger listening on ws://127.0.0.1:9229/8bb6dcc8-a73c-405e-b1fe-69a3d7789a20
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.

然后,Visual Studio Code调试器将

  1. 在程序的第一行停止

  2. 停止在Visual Studio代码编辑器中设置的以下任何断点

答案 11 :(得分:0)

如果您不想对文件名进行硬编码,而是在这里像简单的Grogi's版本一样?使用VS variable reference page中的信息,您可以做两件事:

npm i ts-node

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

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

该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
相关问题