在 GitLab CI/CD 中,为了确保每次部署 Node.js 服务时不需要手动执行 `npm install`,您可以在 `.gitlab-ci.yml` 文件中添加缓存策略来缓存项目依赖。这样,当缓存存在的时候,GitLab Runner 将直接使用缓存的依赖包,从而避免了每次都重新下载。 下面是一个基本示例: ```yaml # .gitlab-ci.yml stages: - build - deploy cache: paths: - node_modules/ build_job: stage: build image: node:latest script: - npm ci # 或者使用 "npm install" 如果你没有 package-lock.json 或 npm-shrinkwrap.json artifacts: paths: - node_modules/ # 将安装好的依赖作为构建产出物保存 deploy_job: stage: deploy image: node:latest before_script: - npm config set prefix "$CI_PROJECT_DIR/node_modules" script: - npm install --production # 在这里,由于我们有缓存,大部分情况下这一步会非常快 - npm start 或其他部署命令... ``` 在这个例子中,`npm ci`(或者根据实际情况选择 `npm install`)会在 `build_job` 阶段执行,并将生成的 `node_modules` 目录添加为构建产出物并缓存。然后,在 `deploy_job` 阶段,由于之前已经缓存了依赖,所以这里的 `npm install --production`(或其他安装步骤)通常会从缓存加载依赖,而不是重新下载。 [2024-02-22 17:39:47 | AI写代码神器 | 339点数解答]