本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
缓存任务结果
在任务执行和缓存等方面,Lerna 和 Nx 可以互换使用。当我们说"Lerna 可以缓存构建"时,实际是指 Lerna 通过 Nx 实现构建缓存。
重复构建和测试相同代码的成本很高。Lerna 通过计算缓存机制确保相同代码永远不会被重复构建。
配置方法
Lerna(通过 Nx)拥有最先进且久经考验的计算缓存系统。它能够判断您即将运行的任务是否已执行过,从而利用缓存恢复该任务的运行结果。
如果尚未创建 nx.json 文件,请运行 npx lerna add-caching。
要为 build 和 test 任务启用缓存,请编辑 nx.json 文件中的 targetDefaults 属性,以包含 build 和 test 任务的配置:
{
"targetDefaults": {
"build": {
"cache": true
},
"test": {
"cache": true
}
}
}
注意:可缓存的操作必须是无副作用的,即相同输入始终产生相同输出。例如,调用后端 API 的端到端测试无法被缓存,因为后端可能影响测试结果。
现在请连续执行两次以下命令,第二次操作将立即完成:
lerna run build --scope=header
> lerna run build --scope=header
> header:build [existing outputs match the cache, left as is]
> header@0.0.0 build
> rimraf dist && rollup --config
src/index.tsx → dist...
created dist in 858ms
—————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
Lerna (powered by Nx) Successfully ran target test for project header (4ms)
Nx read the output from the cache instead of running the command for 1 out of 1 tasks.
缓存回放机制
当 Lerna 检测到任务输入未变化时,会以远超实际执行的速度复现任务输出结果。缓存任务的输出包含终端日志和在指定 output 目录中生成的文件。
您可以通过删除 header:build 任务输出的 dist 文件夹,然后重新运行 lerna run build --scope=header 来验证此机制。缓存任务将瞬间回放,dist 文件夹中会正确生成所有文件。
header/
└── dist/ <-- this folder gets recreated
如果任务输出到其他路径,可更改缓存的输出文件夹。您也可以自定义输入规则来指定哪些变更会使缓存失效。
高级缓存配置
如需深入理解缓存实现原理并针对仓库微调缓存策略,请阅读缓存工作原理。
本地计算缓存
默认情况下,Lerna(通过 Nx)使用本地计算缓存。Nx 仅保留缓存一周,到期后自动清理。执行 nx reset 可立即清除缓存,Nx 将在下次访问时重建新缓存。