在 CI 中使用仓库
CI 使用与开发者工作站相同的 .npmrc(或 .yarnrc.yml)—— 唯一的区别是令牌来自密钥存储而不是磁盘上的文件。
第 1 步:将令牌存为密钥
Section titled “第 1 步:将令牌存为密钥”- 在 Packages → Manage tokens 中签发一个 CI 专用令牌,命名为
ci-github(或类似名称)。为每条流水线使用单独的令牌,这样你可以独立撤销它。 - 将其添加为密钥:
- GitHub Actions → 仓库 Settings → Secrets and variables → Actions →
PIER_NPM_TOKEN。 - GitLab CI → 项目 Settings → CI/CD → Variables →
PIER_NPM_TOKEN(protected、masked)。
- GitHub Actions → 仓库 Settings → Secrets and variables → Actions →
第 2 步:在作业中写入 .npmrc
Section titled “第 2 步:在作业中写入 .npmrc”GitHub Actions —— npm / pnpm / bun
Section titled “GitHub Actions —— npm / pnpm / bun”name: buildon: [push]jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 24 - name: Configure Pier registry run: | cat > .npmrc <<EOF registry=https://YOUR-PIER-HOST/registry/npm/ //YOUR-PIER-HOST/registry/npm/:_authToken=${PIER_NPM_TOKEN} always-auth=true EOF env: PIER_NPM_TOKEN: ${{ secrets.PIER_NPM_TOKEN }} - run: npm ci - run: npm run build对于 pnpm,将 npm ci 替换为 pnpm install --frozen-lockfile;对于 bun,替换为 bun install --frozen-lockfile。
GitHub Actions —— yarn 4(berry)
Section titled “GitHub Actions —— yarn 4(berry)” - name: Configure Pier registry (yarn berry) run: | cat > .yarnrc.yml <<EOF npmRegistryServer: "https://YOUR-PIER-HOST/registry/npm/" npmAuthToken: "${PIER_NPM_TOKEN}" npmAlwaysAuth: true nodeLinker: node-modules EOF env: PIER_NPM_TOKEN: ${{ secrets.PIER_NPM_TOKEN }} - run: corepack enable && yarn install --immutableGitLab CI
Section titled “GitLab CI”build: image: node:24 before_script: - | cat > .npmrc <<EOF registry=https://YOUR-PIER-HOST/registry/npm/ //YOUR-PIER-HOST/registry/npm/:_authToken=${PIER_NPM_TOKEN} always-auth=true EOF script: - npm ci - npm run build第 3 步:从 CI 发布(可选)
Section titled “第 3 步:从 CI 发布(可选)” - name: Publish if: startsWith(github.ref, 'refs/tags/v') run: npm publish env: NPM_CONFIG_REGISTRY: https://YOUR-PIER-HOST/registry/npm/第 2 步写入的 .npmrc 携带了 bearer;npm publish 会自动取用它。
- 每条流水线一个令牌。 撤销时不影响其他任何东西。
always-auth=true是必需的,对 yarn 1 而言;对 npm/pnpm/bun 无害。yarn 4 需要在.yarnrc.yml中设置npmAlwaysAuth: true。- 在多次运行之间缓存
node_modules。 代理很快,但完全跳过安装更快 —— 使用标准的 actions/setup-node 缓存。 - 在安装前验证仓库可达 —— 一行
curl -sf https://your-pier-host/registry/npm/-/ping能在 Traefik 或 DNS 出问题时,免去一次令人困惑的 5 分钟安装报错。