全局 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. 最佳实践总结
- 开发环境:使用宽松的 SSL 设置,开发版 Nexus
- 测试环境:镜像生产环境配置,但可禁用 SSL
- 生产环境:严格的 SSL 验证,生产版 Nexus
- 认证信息:使用环境变量,不硬编码在配置文件中
- 切换便利:提供一键切换环境的脚本
这样配置可以实现灵活的多环境管理,确保不同环境使用正确的 npm 仓库配置。