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

3
我有一个针对 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,命令执行成功。

1个回答

4

在进行任何其他操作之前,请安装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的用途。

请注意,我不明白为什么要在构建之后运行npm doctor。假设您关心npm是否正确设置,应该在构建之前运行它,以使流水线尽早失败。

P.S. 我愚蠢地将“github”读成“gitlab”。如果您正在使用github,则建议仅出于依赖项缓存的目的使用setup-node,这可以大大加快流水线速度。 我不知道gitlab是否会做类似的事情。


我在 npm doctornpm ci 之前添加了 npm install npm@7.24.0,但是在 npm -v 上仍然抛出相同的错误。另外,我正在寻找 GitLab 的 setup-node - adrisons
抱歉,对于系统范围,您需要使用“-g”。我不记得您是否可以在GitLab CI环境中这样做。否则,您可以运行本地npm。 - 2e0byo
编辑以覆盖本地安装情况。 - 2e0byo
非常感谢,使用-g选项它起作用了!但npx选项没有。 - adrisons

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接