全局 npm config 与多环境配置

全局 npm config 与多环境配置

1. 全局 npm config 配置方法

查看当前全局配置
bash 复制代码
npm config list
# 或
npm config list -l
设置全局配置
bash 复制代码
# 设置默认注册表
npm config set registry https://registry.npmjs.org/

# 设置代理
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080

# 设置严格SSL验证
npm config set strict-ssl true

# 设置超时时间
npm config set timeout 60000

# 设置缓存目录
npm config set cache /path/to/npm-cache

# 设置全局安装目录
npm config set prefix /usr/local/npm-global
常用全局配置命令
bash 复制代码
# 查看特定配置
npm config get registry
npm config get proxy

# 删除配置
npm config delete proxy
npm config delete https-proxy

# 编辑配置文件
npm config edit

2. 多环境配置方案

方案一:环境变量 + .npmrc 文件

项目结构:

复制代码
my-project/
├── .npmrc              # 开发环境(默认)
├── .npmrc.production   # 生产环境
├── .npmrc.testing      # 测试环境
├── package.json
└── scripts/
    └── switch-npmrc.js

环境特定的 .npmrc 文件:

.npmrc (开发环境)

ini 复制代码
registry=http://nexus-dev.company.com/repository/npm-group/
@my-company:registry=http://nexus-dev.company.com/repository/npm-private/
//nexus-dev.company.com/:_authToken=${NPM_TOKEN}
cache=/tmp/npm-cache

.npmrc.production

ini 复制代码
registry=http://nexus-prod.company.com/repository/npm-group/
@my-company:registry=http://nexus-prod.company.com/repository/npm-private/
//nexus-prod.company.com/:_authToken=${NPM_TOKEN}
cache=/tmp/npm-cache
strict-ssl=true

.npmrc.testing

ini 复制代码
registry=http://nexus-test.company.com/repository/npm-group/
@my-company:registry=http://nexus-test.company.com/repository/npm-private/
//nexus-test.company.com/:_authToken=${NPM_TOKEN}
cache=/tmp/npm-cache
strict-ssl=false
方案二:使用环境变量动态配置

package.json 脚本配置:

json 复制代码
{
  "scripts": {
    "install:dev": "NPM_CONFIG_REGISTRY=http://nexus-dev.company.com/repository/npm-group/ npm install",
    "install:test": "NPM_CONFIG_REGISTRY=http://nexus-test.company.com/repository/npm-group/ npm install",
    "install:prod": "NPM_CONFIG_REGISTRY=http://nexus-prod.company.com/repository/npm-group/ npm install",
    "publish:dev": "NPM_CONFIG_REGISTRY=http://nexus-dev.company.com/repository/npm-private/ npm publish",
    "publish:prod": "NPM_CONFIG_REGISTRY=http://nexus-prod.company.com/repository/npm-private/ npm publish",
    "switch:dev": "node scripts/switch-npmrc.js dev",
    "switch:test": "node scripts/switch-npmrc.js test",
    "switch:prod": "node scripts/switch-npmrc.js prod"
  }
}

切换脚本 (scripts/switch-npmrc.js):

javascript 复制代码
const fs = require('fs');
const path = require('path');

const env = process.argv[2];
const configFiles = {
  dev: '.npmrc',
  test: '.npmrc.testing',
  prod: '.npmrc.production'
};

if (!configFiles[env]) {
  console.error('Usage: node switch-npmrc.js [dev|test|prod]');
  process.exit(1);
}

const sourceFile = path.join(__dirname, '..', configFiles[env]);
const targetFile = path.join(__dirname, '..', '.npmrc');

try {
  fs.copyFileSync(sourceFile, targetFile);
  console.log(`✅ Switched to ${env} environment`);
} catch (error) {
  console.error(`❌ Failed to switch environment: ${error.message}`);
  process.exit(1);
}
方案三:使用 dotenv 和自定义脚本

.env.development

ini 复制代码
NPM_REGISTRY=http://nexus-dev.company.com/repository/npm-group/
NPM_PRIVATE_REGISTRY=http://nexus-dev.company.com/repository/npm-private/
NPM_STRICT_SSL=false

.env.production

ini 复制代码
NPM_REGISTRY=http://nexus-prod.company.com/repository/npm-group/
NPM_PRIVATE_REGISTRY=http://nexus-prod.company.com/repository/npm-private/
NPM_STRICT_SSL=true

动态生成 .npmrc 脚本:

javascript 复制代码
// scripts/generate-npmrc.js
const fs = require('fs');
require('dotenv').config({ path: `.env.${process.env.NODE_ENV || 'development'}` });

const npmrcContent = `
registry=${process.env.NPM_REGISTRY}
@my-company:registry=${process.env.NPM_PRIVATE_REGISTRY}
//nexus.company.com/:_authToken=${process.env.NPM_TOKEN}
strict-ssl=${process.env.NPM_STRICT_SSL}
always-auth=true
`.trim();

fs.writeFileSync('.npmrc', npmrcContent);
console.log('✅ .npmrc generated for', process.env.NODE_ENV || 'development');

3. CI/CD 环境配置

GitHub Actions 示例
yaml 复制代码
# .github/workflows/deploy.yml
jobs:
  deploy:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        environment: [dev, test, prod]
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          registry-url: ${{ matrix.environment == 'prod' && 'https://nexus-prod.company.com/repository/npm-group/' || 'https://nexus-dev.company.com/repository/npm-group/' }}
          
      - name: Setup npm authentication
        run: |
          echo "//nexus-${{ matrix.environment }}.company.com/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
          echo "always-auth=true" >> .npmrc
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run tests
        run: npm test
        
      - name: Build and deploy
        run: npm run deploy:${{ matrix.environment }}
Jenkins Pipeline 示例
groovy 复制代码
pipeline {
    agent any
    parameters {
        choice(
            name: 'ENVIRONMENT',
            choices: ['dev', 'test', 'prod'],
            description: 'Target environment'
        )
    }
    environment {
        NPM_REGISTRY = {
            dev -> 'http://nexus-dev.company.com/repository/npm-group/'
            test -> 'http://nexus-test.company.com/repository/npm-group/'
            prod -> 'http://nexus-prod.company.com/repository/npm-group/'
        }[params.ENVIRONMENT]
    }
    stages {
        stage('Setup') {
            steps {
                sh '''
                    npm config set registry ${NPM_REGISTRY}
                    npm config set //nexus-${ENVIRONMENT}.company.com/:_authToken ${NPM_TOKEN}
                    npm config set always-auth true
                '''
            }
        }
        stage('Install') {
            steps {
                sh 'npm ci'
            }
        }
    }
}

4. Docker 多环境配置

Dockerfile:

dockerfile 复制代码
FROM node:18-alpine

# 构建参数,指定环境
ARG NODE_ENV=production
ARG NPM_REGISTRY=https://registry.npmjs.org/

# 设置环境变量
ENV NODE_ENV=$NODE_ENV
ENV NPM_CONFIG_REGISTRY=$NPM_REGISTRY

WORKDIR /app

# 复制 package 文件
COPY package*.json ./

# 根据环境安装依赖
RUN if [ "$NODE_ENV" = "development" ]; then \
        npm install; \
    else \
        npm ci --only=production; \
    fi

# 复制源代码
COPY . .

# 根据环境执行不同命令
CMD if [ "$NODE_ENV" = "development" ]; then \
        npm run dev; \
    else \
        npm start; \
    fi

docker-compose.yml:

yaml 复制代码
version: '3.8'
services:
  app-dev:
    build:
      context: .
      args:
        NODE_ENV: development
        NPM_REGISTRY: "http://nexus-dev.company.com/repository/npm-group/"
    environment:
      - NODE_ENV=development
    volumes:
      - .:/app
      - /app/node_modules

  app-prod:
    build:
      context: .
      args:
        NODE_ENV: production
        NPM_REGISTRY: "http://nexus-prod.company.com/repository/npm-group/"
    environment:
      - NODE_ENV=production

5. 最佳实践总结

  1. 开发环境:使用宽松的 SSL 设置,开发版 Nexus
  2. 测试环境:镜像生产环境配置,但可禁用 SSL
  3. 生产环境:严格的 SSL 验证,生产版 Nexus
  4. 认证信息:使用环境变量,不硬编码在配置文件中
  5. 切换便利:提供一键切换环境的脚本

这样配置可以实现灵活的多环境管理,确保不同环境使用正确的 npm 仓库配置。

相关推荐
QQ1__8115175157 小时前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态7 小时前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子7 小时前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室7 小时前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI7 小时前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing7 小时前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者7 小时前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册7 小时前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李7 小时前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢7 小时前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web