GitHub Action中npm依赖缓存无法正常工作的问题排查
问题分析与解决方案
核心问题原因
你当前缓存的是npm全局缓存目录~/.npm,这个目录仅存储npm下载的包压缩包;而项目运行依赖的是repo/node_modules目录下已解压的实际依赖文件。因此:
- 即使恢复了
~/.npm缓存,npm ci仍需将压缩包解压到node_modules,这会消耗时间 - 缓存恢复后直接执行
npm list会报错,因为此时node_modules目录尚未生成(npm ci还未执行)
修复方案一:手动缓存node_modules与全局缓存
修改缓存路径,同时包含项目的node_modules和npm全局缓存,让npm ci在缓存命中时无需重新解压或下载:
- name: Setup NodeJS uses: actions/setup-node@v3 with: node-version: ${{ env.nodejs_version }} - name: Restore npm cache uses: actions/cache/restore@v3 id: cache-npm-restore with: path: | ~/.npm ${{ env.repo_dir }}/node_modules key: ${{ runner.os }}-build-${{ env.cache_name }}-${{ hashFiles('repo/package-lock.json') }} - name: Install NodeJS modules (only if cache miss) run: cd $repo_dir && npm ci if: ${{ steps.cache-npm-restore.outputs.cache-hit != 'true' }} - name: Save npm cache uses: actions/cache/save@v3 if: ${{ steps.cache-npm-restore.outputs.cache-hit != 'true' }} with: path: | ~/.npm ${{ env.repo_dir }}/node_modules key: ${{ steps.cache-npm-restore.outputs.cache-primary-key }} - name: List node modules state (after install/cache restore) continue-on-error: true run: cd $repo_dir && npm list
修复方案二:使用actions/setup-node自带缓存(推荐)
actions/setup-node v3及以上版本已集成缓存功能,无需手动调用actions/cache,配置更简洁可靠:
- name: Setup NodeJS with cache uses: actions/setup-node@v3 with: node-version: ${{ env.nodejs_version }} cache: 'npm' cache-dependency-path: ${{ env.repo_dir }}/package-lock.json - name: Install NodeJS modules run: cd $repo_dir && npm ci - name: List node modules state continue-on-error: true run: cd $repo_dir && npm list
该配置会自动处理缓存的恢复与保存,默认包含~/.npm和项目node_modules目录。
内容的提问来源于stack exchange,提问作者vy218
相关产品推荐
相关产品推荐

