GitHub Action中npm run build超时失败,本地及Vercel可正常运行
问题描述
我正在构建一个Vue应用,遇到以下问题:
- GitHub Action中执行
npm run build耗时远超本地,甚至超出10分钟的超时限制 - 本地执行
npm run build可正常完成,前端部署到Vercel时该命令也能正常运行 - 已尝试将
npm i替换为npm ci,但问题仍未解决
附当前GitHub Action配置:
--- name: CI Workflow on: pull_request: concurrency: group: ${{ github.ref }}-ci-workflow jobs: build: runs-on: ubuntu-latest continue-on-error: false timeout-minutes: 10 steps: - name: Checkout code uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: "18" - name: Install Dependencies run: | cd frontend npm ci - name: Build code run: | cd frontend npm run build test: runs-on: ubuntu-latest continue-on-error: false timeout-minutes: 5 steps: - name: Checkout code uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v4 with: python-version: "3.9" - name: Install Dependencies run: | cd backend pip install -r requirements.txt - name: Test backend code using pytest run: | cd backend pytest tests
解决方法
启用依赖缓存:GitHub Action默认不缓存
node_modules,每次重新安装会增加IO开销。给依赖安装步骤加上缓存:- name: Install Dependencies run: | cd frontend npm ci uses: actions/cache@v3 with: path: | frontend/node_modules key: ${{ runner.os }}-node-${{ hashFiles('frontend/package-lock.json') }} restore-keys: | ${{ runner.os }}-node-优化Vue构建配置:修改构建配置,关闭不必要的耗时选项:
- 禁用生产环境sourcemap,能大幅减少构建时间:
// vue.config.js module.exports = { productionSourceMap: false } - 如果用Vite,可启用构建缓存、替换压缩工具(比如用esbuild代替terser)来提速。
- 禁用生产环境sourcemap,能大幅减少构建时间:
升级Runner资源:默认
ubuntu-latest是2核CPU,若仓库在GitHub付费计划内,可改用更大规格的Runner:runs-on: ubuntu-latest-xl排查构建瓶颈:开启构建详细日志,定位耗时环节:
- name: Build code run: | cd frontend export CI=true npm run build --verbose根据日志判断是依赖编译、资源打包还是其他步骤拖慢了速度。
清理冗余依赖/插件:检查
package.json中的开发依赖,移除不必要的构建插件,或替换为更高效的替代方案——部分插件在GitHub Action环境下的编译效率可能和本地、Vercel有差异。
内容的提问来源于stack exchange,提问作者chulin
相关产品推荐
相关产品推荐

