求可正常工作的VSCode tasks.json配置:ng build --watch与ng lint
适用于Angular CLI的VS Code tasks.json配置方案
我之前也碰到过一模一样的问题——ng build --watch修复代码后旧错误还留在问题标签页,还有ng lint任务跑不起来的情况。下面是我反复测试过、可以正常工作的tasks.json完整配置,包含这两个任务的正确定义:
{ "version": "2.0.0", "tasks": [ // 带watch模式的Angular构建任务 { "label": "ng build: watch", "type": "shell", "command": "ng build --watch", "options": { "cwd": "${workspaceFolder}" }, "isBackground": true, "problemMatcher": { "base": "$tsc-watch", "fileLocation": "absolute", "watcher": { "activeOnStart": true, "beginsPattern": ".*Compiling.*", "endsPattern": ".*Compiled successfully.*|.*Failed to compile.*" } }, "group": { "kind": "build", "isDefault": false } }, // Angular代码检查任务 { "label": "ng lint", "type": "shell", "command": "ng lint", "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": { "owner": "typescript", "fileLocation": "absolute", "pattern": { "regexp": "^(.*?)(\\((\\d+),(\\d+)\\))?:\\s+(error|warning|info)\\s+(TS\\d+):\\s+(.*)$", "file": 1, "line": 3, "column": 4, "severity": 5, "code": 6, "message": 7 } }, "group": { "kind": "test", "isDefault": false } } ] }
关键配置说明
ng build --watch核心修复点- 设置
isBackground: true:因为watch模式是持续运行的后台任务,VS Code需要识别这一点才能正确管理任务状态 - 自定义
watcher规则:通过匹配Angular CLI的编译输出(比如Compiling...开始,Compiled successfully或Failed to compile结束),让VS Code知道什么时候该清除旧的错误列表,重新加载新的编译结果——这就是解决修复错误后旧问题不消失的关键! - 基于
$tsc-watch基础匹配器:复用TypeScript watch模式的问题匹配逻辑,完美适配Angular CLI的输出格式
- 设置
ng lint配置说明- 自定义的
pattern规则:精准匹配Angular CLI lint命令的输出格式,确保所有lint错误、警告都能正确解析并显示在VS Code的问题标签页,点击错误就能直接跳转到对应代码位置 - 归类到
test组:方便在任务面板中快速找到代码检查类任务
- 自定义的
使用方法
- 按
Ctrl+Shift+B(Windows/Linux)或Cmd+Shift+B(Mac)打开任务面板,选择对应的任务运行即可 ng build: watch运行后,修改代码修复错误,编译成功后旧的错误会自动从问题标签页移除ng lint运行后,所有lint问题会一次性展示在问题标签中,支持快速定位修复
内容的提问来源于stack exchange,提问作者Omtechguy




