前端工程的环境变量,通常会使用cross-env在package.json的scripts中设置
"scripts": { "serve": "cross-env NODE_ENV=development META_BASE=meta.dev.com vue-cli-service serve --open", "build": "cross-env NODE_ENV=production META_BASE=meta.online.com vue-cli-service build" }
这样设置环境变量,有以下缺点:
1. scripts命令过长,书写不方便
2. 变量混杂在一行,查看不方便
3. 多环境的环境变量引入,需要添加多个额外的命令
例如:在环境1和环境2各自有开发,生产和测试,要添加如下
"scripts": { "dev:env1": "cross-env NODE_ENV=development META_BASE=meta.dev.com vue-cli-service serve --open", "pro:env1": "cross-env NODE_ENV=production META_BASE=meta.online.com vue-cli-service build", "test:env1": "cross-env NODE_ENV=test META_BASE=meta.online.com vue-cli-service build", "dev:env2": "cross-env NODE_ENV=development META_BASE=meta.dev.com vue-cli-service serve --open", "pro:env2": "cross-env NODE_ENV=production META_BASE=meta.online.com vue-cli-service build", "test:env2": "cross-env NODE_ENV=test META_BASE=meta.online.com vue-cli-service build", }
推荐使用env-cmd这个组件,来设置环境变量,集中在一个环境文件中,简单方便,多环境书写尤其方便。
"scripts": { "dev": "env-cmd -e dev -f ./.env-cmdrc.json node index.js" }
env-cmdrc.json
{ "dev": { "ENV1": "Thanks dev", "ENV2": "For All dev" }, "test": { "ENV1": "Thanks test", "ENV2": "For All test" }, "prod": { "ENV1": "Thanks prod", "ENV2": "For All prod" }, "hw:prod": { "ENV1": "Thanks hw:prod", "ENV2": "For All hw:prod" } }
环境变量使用,与package.json的script命令中-e后面的环境对应,上面配置的为dev环境
let env = process.env; console.log('env1 ',env.ENV1); console.log('env2 ',env.ENV2);