如何在 gitlab CI 中设置 npm 版本?

How can I set the npm version in gitlab CI?

我有一个 Angular 项目的 gitlab 管道,图像在 .gitlab-ci.yml

image: node:16


build:
  stage: build
  script:
    - npm ci
    - nodejs -v
    - npm -v
    - npm run build:prod
    - npm doctor

当管道到达 npm doctor 时,它失败并在 npm 版本上出现以下错误:

$ npm doctor
Check                               Value   Recommendation/Notes
npm ping                            ok
npm -v                              not ok  Use npm v7.24.0
node -v                             ok      current: v16.9.1, recommended: v16.9.1
npm config get registry             ok      using default registry (https://registry.npmjs.org/)
which git                           ok      /usr/bin/git
Perms check on cached files         ok
Perms check on local node_modules   ok
Perms check on global node_modules  ok
Perms check on local bin folder     ok
Perms check on global bin folder    ok
Verify cache contents               ok      verified 1361 tarballs

我该如何解决这个问题?

在我的机器上我有 npm 版本 v7.24.0 并且命令成功。

在执行任何其他操作之前安装 npm,指定版本,即 npm install npm@version -g

为了完整起见,如果您无法更新全局 npm,您可以在本地更新,方法是将 npm 替换为 npx npm@latestnpx npm@7.24.0。如果需要,npx 将安装 npm,本地,然后 运行 本地安装。

最后,您可以使用 npm install npm@latest 在本地安装,然后使用 $(npm bin)/npm 运行 安装它,但这就是 npx 的用途。

请注意,我不明白为什么 运行ning npm doctor 构建之后。据推测,如果您关心 npm thining 它的设置是否正确,您应该 运行 在 构建之前 它,因此管道会提前失败。

P.S。我傻傻的把'github'读成了'gitlab'。如果您使用 github 我建议您使用 setup-node 如果仅用于依赖项缓存,这会严重加速管道。不知道gitlab有没有类似的东西