注入环境
通过 自定义变量 process.env.DEPLOY_ENV 注入环境信息
1. 通过 package.json 中,export NODE_ENV=production 注入
普通注入
start 时注入 development,runTest时注入test,build 时注入 production,runProd 时注入 production 等等。
"scripts": {
"start": "export DEPLOY_ENV=development && yarn dev",
"runTest": "export DEPLOY_ENV=test && npm run serve",
"runProd": "export DEPLOY_ENV=production && npm run serve",
"build": "export NODE_ENV=production && ../../node_modules/.bin/tsc"
},
node 脚本打印
console.log(process.env.DEPLOY_ENV);
cross
"scripts": {
"local": "cross-env NODE_ENV=local DEBUG=NodeThrift ./node_modules/.bin/supervisor --inspect -w server/plugin index.js",
"build:test": "cross-env NODE_ENV=test ./node_modules/@fdfe/era-build/bin/era-build",
"build:prod": "cross-env NODE_ENV=prod ./node_modules/@fdfe/era-build/bin/era-build",
"build-dll": "./node_modules/@fdfe/era-build/bin/era-build-dll",
"lint": "eslint --ext .js server --fix",
"test": "era-bin test"
},
node 脚本打印
console.log(process.env.DEPLOY_ENV);
2. 通过 shell 脚本
shell 脚本
export DEPLOY_ENV=production
echo $DEPLOY_ENV
node 脚本打印
console.log(process.env.DEPLOY_ENV);
部署
有很多种部署环境的方式,但基本上原理一致,在不同环境部署的时候读取不同的文件:
测试环境: 读取 deploy/sh/test.sh
预发环境: 读取 deploy/sh/staging.sh
线上环境: 读取 deploy/sh/prod.sh
读取
写上不同环境的配置后,通过 process.env.DEPLOY_ENV 判断,返回不同的host
const devConfig = {
host: '127.0.0.1:8080',
}
const testConfig = {
host: 'http://myhost.test.com',
othersystemHost: 'http://othersystem.test.com',
}
const prodConfig = {
host: 'http://myhost.com',
othersystemHost: 'http://othersystem.com',
}
export function currentInitConfig(): InitConfigType {
// 通过 process.env.DEPLOY_ENV判断环境
switch (process.env.DEPLOY_ENV) {
case 'develop':
return devConfig;
case 'test':
return testConfig;
case 'production':
return prodConfig;
default:
return devConfig;
}
}