6月2日 01:13

VSCode 任务系统怎么用?tasks.json 配置和自动化构建实战

VSCode 的任务系统让你把常用命令(构建、测试、部署)绑定为任务,按 Ctrl+Shift+B 直接运行,不用每次手敲终端命令。

最简单的任务

json
// .vscode/tasks.json { "version": "2.0.0", "tasks": [ { "label": "build", "type": "shell", "command": "npm run build" } ] }

运行:Ctrl+Shift+P 输入 Tasks: Run Task,选择 "build"。或者 Tasks: Run Build Task(Ctrl+Shift+B)直接运行标记为 build group 的任务。

常用任务配置

json
{ "version": "2.0.0", "tasks": [ { "label": "dev", "type": "shell", "command": "npm run dev", "isBackground": true, "problemMatcher": [] }, { "label": "build", "type": "shell", "command": "npm run build", "group": { "kind": "build", "isDefault": true }, "problemMatcher": ["$tsc"] }, { "label": "test", "type": "shell", "command": "npm test", "group": { "kind": "test", "isDefault": true } } ] }

关键配置项:

  • group: "build":标记为构建任务,Ctrl+Shift+B 直接触发
  • group: "test":标记为测试任务,可以在菜单里一键跑
  • isBackground: true:后台运行(dev server 这种不会自动退出的命令必须加)
  • problemMatcher:解析终端输出中的错误,映射到编辑器的 Problems 面板

problemMatcher:自动捕获错误

$tsc 是内置的 TypeScript 编译器匹配器,自动把 src/main.ts(10,5): error TS2304 这种输出映射到编辑器的问题面板。

自定义匹配器(捕获 ESLint 错误):

json
{ "label": "lint", "type": "shell", "command": "npx eslint src/", "problemMatcher": { "owner": "eslint", "fileLocation": "relative", "pattern": { "regexp": "^(.+):(\d+):(\d+)\s+-\s+(.+)$", "file": 1, "line": 2, "column": 3, "message": 4 } } }

正则捕获的文件名、行号、列号映射到编辑器,点击错误直接跳转。

任务间依赖

多个任务按顺序执行:

json
{ "label": "deploy", "dependsOn": ["build", "test"], "dependsOrder": "sequence" }

dependsOrder: "sequence" 串行执行(先 build 再 test),不加则是并行。

输入变量

任务支持变量替换,不用硬编码路径:

json
{ "label": "run current file", "type": "shell", "command": "python ${file}" }

常用变量:${file}(当前文件)、${workspaceFolder}(项目根目录)、${fileBasenameNoExtension}(文件名不含后缀)。

preLaunchTask:调试前自动跑任务

在 launch.json 里配 preLaunchTask,按 F5 调试时自动先跑构建任务:

json
// .vscode/launch.json { "configurations": [ { "type": "node", "request": "launch", "name": "Debug", "program": "${workspaceFolder}/dist/index.js", "preLaunchTask": "build" } ] }

这样调试时不会遇到"代码改了但跑的是旧构建"的问题。

标签:VSCode