You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过NVM在CI服务器中同时使用不同Node.js版本?

Can I Use Different Node Versions Simultaneously for Two Projects in CI?

Absolutely you can! The issue you’re facing right now is that nvm use modifies the current shell session’s environment variables (like updating your PATH to point to the selected Node version). If both projects’ build scripts run in the same shell, the second nvm use call will overwrite the first one, forcing both builds to use the same version.

Here are the most reliable fixes tailored for CI environments:

1. Use nvm exec to Isolate Each Project’s Environment

Instead of relying on a global nvm use call, use nvm exec to run your build commands in a subshell with the target Node version. This way, each project’s build uses its own version without affecting the other.

For example:

  • For Project A (Node 16):
    nvm exec 16 npm run build
    
  • For Project B (Node 20):
    nvm exec 20 npm run build
    

To make this more maintainable, add a .nvmrc file to each project’s root with just the version number (e.g., 16 or 20.10.0). Then your build command can dynamically read the version:

nvm exec $(cat .nvmrc) npm run build

2. Split Builds into Separate CI Jobs

Most CI platforms (like GitLab CI, GitHub Actions, Jenkins) let you run jobs in isolated environments. Split your two projects into separate CI jobs—each job can initialize its own Node version independently, with no cross-contamination.

For example, in a GitLab CI config:

build-project-a:
  script:
    - source ~/.nvm/nvm.sh
    - nvm use 16
    - npm install
    - npm run build

build-project-b:
  script:
    - source ~/.nvm/nvm.sh
    - nvm use 20
    - npm install
    - npm run build

These jobs run in separate containers/shells, so their Node versions never interfere with each other.

3. Directly Call the Node Binary Path

If nvm exec isn’t working for some reason, you can directly reference the full path to the Node binary installed by NVM. You can find the path using nvm which <version> (e.g., nvm which 16 returns something like ~/.nvm/versions/node/v16.18.0/bin/node).

Then use that path to run your npm commands:

~/.nvm/versions/node/v16.18.0/bin/npm run build

Quick Pre-Check

Make sure both Node versions are installed on your CI server. Run nvm ls in your CI initialization step to verify—if a version is missing, add nvm install <version> to your script to install it on demand.

内容的提问来源于stack exchange,提问作者AnuragNayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:58:24