Lint-staged+Vitest预提交钩子运行关联测试耗时过长求助
问题分析与解决方案
现状与核心矛盾
我有两个独立项目,分别放在app和backoffice目录下,当前package.json配置如下:
{ "scripts": { "start": "cd app && yarn start", "test": "cd app && vitest related --run --passWithNoTests", "prepare": "husky install", "test-backoffice": "cd backoffice && vitest related --run --passWithNoTests" }, "lint-staged": { "*.(js|jsx|ts|tsx)": [ "yarn test", "yarn test-backoffice" ] } }
现在遇到两个无法兼顾的问题:
- 移除
related参数:测试执行速度快,但修改源码文件(如fullname.ts)时,无法触发对应的测试文件(fullname.test.ts)运行 - 保留
related参数:测试耗时过长,控制台显示总时长(19.14s)远大于各阶段耗时总和(transform 496ms + setup 121ms + collect 787ms + tests 11ms + environment 224ms + prepare 49ms ≈ 1.7s)
解决方案
1. 拆分lint-staged规则,避免冗余测试执行
当前lint-staged会对所有JS/TS文件执行两个目录的测试,哪怕只修改了其中一个目录的文件,这会造成大量不必要的耗时。可以按目录拆分规则,只执行对应项目的测试:
"lint-staged": { "app/**/*.(js|jsx|ts|tsx)": [ "yarn test" ], "backoffice/**/*.(js|jsx|ts|tsx)": [ "yarn test-backoffice" ] }
2. 优化vitest related参数的扫描范围
默认的related参数会扫描整个项目的依赖关系,可能因为目录结构复杂导致性能问题。可以明确指定测试文件的匹配路径,缩小扫描范围:
"scripts": { "start": "cd app && yarn start", "test": "cd app && vitest related --run --passWithNoTests src/**/*.test.{ts,tsx}", "prepare": "husky install", "test-backoffice": "cd backoffice && vitest related --run --passWithNoTests src/**/*.test.{ts,tsx}" }
3. 排查vitest依赖解析的额外耗时
总时长远大于阶段总和,大概率是依赖解析环节存在隐性阻塞。可以尝试:
- 清理缓存与依赖:执行
yarn cache clean后重新yarn install,排除缓存污染问题 - 升级vitest到最新稳定版,官方可能已经修复了相关性能Bug
- 开启vitest调试模式:添加
--inspect参数,查看是否有进程阻塞或资源占用异常的情况
内容的提问来源于stack exchange,提问作者Żywy
相关产品推荐
相关产品推荐

