使用VSCode的Task自动编译和调试Typescript项目

2,381 阅读1分钟

使用VSCode的Task自动编译和调试Typescript项目

VSCode可以在调试配置中预先调用编译任务,这样就可以调试时自动编译Typescript项目。

配置

可以通过菜单栏Terrminal->Configure TasksRun->Add Configuration来生成配置模板文件,然后修改需要的选项。

.vscode/tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "typescript",
      "tsconfig": "tsconfig.json",
      "option": "watch",
      "problemMatcher": ["$tsc-watch"],
      "label": "tsc: watch - tsconfig.json",
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "isBackground": true,
      "presentation": {
        "reveal": "never"
      }
    }
  ]
}

解释:

  • "type":自定义任务类型
  • "tsconfig":定义TS构建的tsconfig配置文件
  • "option":选项,这里选tsc的监听文件改动自动编译模式。
  • "problemMatcher":错误匹配器选ts对应的。
  • "label":任务名称。
  • "group":定义此任务属于哪个执行组,编译或测试
    • "kind":设为编译组。
    • "isDefault":设为默认任务,可以被默认调用。
  • "isBackground":后台任务,不会等待任务结束。
  • "presentation":配置用于显示任务输出和读取其输入的面板。
    • "reveal":执行时不弹出显示。

.vscode/launch.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",
      "name": "Launch Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/dist/index.js",
      "outFiles": ["${workspaceFolder}/**/*.js"],
      "preLaunchTask": "${defaultBuildTask}",
      "console": "integratedTerminal"
    }
  ]
}

解释:

  • "type":配置的类型
  • "request":配置的请求类型
  • "name":配置的名称
  • "skipFiles":跳过所有nodejs内置模块
  • "program":运行入口
  • "outFiles":指明有sourcemap时哪里去找生成的js文件位置
  • "preLaunchTask":调试前运行的任务,这里调用编译组的默认任务
  • "console":调试运行的目标,三种分别如下:
    • "internalConsole":内置控制台,有repl,但stdout, stderr输出和普通终端不同。
    • "integratedTerminal":整合的系统终端,基本一模一样。偶尔在Ubuntu中文字体显示有问题。
    • "extenalTerminal":直接启动系统终端。

tsconfig.json

{
  "target": "ES2017",  
  "outDir": "./out",            /* Redirect output structure to the directory. */
  "rootDir": "./src", 
}

解释:

  • "target":为了更好的调试堆栈跟踪,ts编译目标应该选择ES2017以上支持原生异步的。否则编译后的代码堆栈可能变化很大会很乱。
  • "outDir":输出目录
  • "rootDir":输入目录

参考

  1. Debugging in Visual Studio Code