VS Code 任务系统与自动化构建
VS Code 任务系统允许在编辑器内定义和运行外部工具,实现自动化构建、测试、部署等流程。任务配置存储在 .vscode/tasks.json 文件中。
任务配置基础
创建任务配置
通过菜单:Terminal > Configure Tasks 或手动创建 .vscode/tasks.json:
json{ "version": "2.0.0", "tasks": [ { "label": "build", "type": "npm", "script": "build", "problemMatcher": "$tsc" } ] }
任务类型
npm 任务
使用 npm scripts:
json{ "label": "npm: build", "type": "npm", "script": "build", "group": "build" }
Shell 任务
执行 shell 命令:
json{ "label": "echo", "type": "shell", "command": "echo", "args": ["Hello World"] }
Process 任务
直接运行进程:
json{ "label": "run server", "type": "process", "command": "node", "args": ["server.js"], "isBackground": true }
任务属性
常用属性
label: 任务显示名称type: 任务类型(shell, process, npm)command: 要执行的命令args: 命令参数options: 选项(cwd, env 等)group: 任务分组(build, test, none)dependsOn: 依赖的其他任务problemMatcher: 问题匹配器
任务分组
json{ "label": "build", "type": "npm", "script": "build", "group": { "kind": "build", "isDefault": true } }
问题匹配器
问题匹配器将任务输出转换为可点击的错误链接:
内置匹配器
$tsc: TypeScript 编译器$eslint: ESLint$jshint: JSHint$go: Go 编译器
自定义匹配器
json{ "label": "lint", "type": "shell", "command": "eslint", "args": ["src/**/*.js"], "problemMatcher": { "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "message": 4 } } }
任务依赖
定义任务之间的依赖关系:
json{ "version": "2.0.0", "tasks": [ { "label": "clean", "type": "shell", "command": "rm", "args": ["-rf", "dist"] }, { "label": "build", "dependsOn": ["clean"], "type": "npm", "script": "build" } ] }
多任务配置
构建和测试
json{ "version": "2.0.0", "tasks": [ { "label": "build", "type": "npm", "script": "build", "group": "build" }, { "label": "test", "type": "npm", "script": "test", "group": "test" } ] }
自动检测任务
VS Code 可以自动检测常见构建工具的任务:
- npm scripts
- Gulp
- Grunt
- Jake
- Maven
任务运行方式
- 命令面板: Ctrl+Shift+P > "Tasks: Run Task"
- 快捷键: 绑定自定义快捷键
- 从任务列表: Terminal > Run Task
注意事项
- 任务配置应提交到版本控制
- 使用
isBackground: true标记长时间运行的任务 - 合理使用问题匹配器提高开发效率
- 考虑跨平台兼容性(Windows/Linux/macOS)
- 复杂构建流程可以使用 dependsOn 组织