使用env-cmd代替cross-env设置环境变量
前端工程的环境变量,通常会使用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": { "env1:dev": "cross-env NODE_ENV=development META_BASE=meta.dev.com vue-cli-service serve --open", "env1:pro": "cross-env NODE_ENV=production META_BASE=meta.online.com vue-cli-service build", "env1:test": "cross-env NODE_ENV=test META_BASE=meta.online.com vue-cli-service build", "env2:dev": "cross-env NODE_ENV=development META_BASE=meta.dev.com vue-cli-service serve --open", "env2:pro": "cross-env NODE_ENV=production META_BASE=meta.online.com vue-cli-service build", "env2:test": "cross-env NODE_ENV=test META_BASE=meta.online.com vue-cli-service build", }
推荐使用env-cmd这个组件,来设置环境变量,集中在一个环境文件中,简单方便,多环境书写尤其方便。
"scripts": { "yy:dev": "env-cmd -e yy:dev node index.js", "yy:test": "env-cmd -e yy:test -f .env-cmdrc.js node index.js", "yy:prod": "env-cmd -e yy:prod node index.js", "hw:dev": "env-cmd -e hw:dev node index.js", "hw:test": "env-cmd -e hw:test node index.js", "hw:prod": "env-cmd -e hw:prod node index.js" }
.env-cmdrc.js
在js文件中,可以编写代码,变量可以复用
let var1 = 'var1-env'; let var2 = 'var2-env'; module.exports = { "yy:dev": { "var1": `dev ${var1}`, "var2": `dev ${var2}` }, "yy:test": { "var1": "test var1", "var2": "test var2" }, "yy:prod": { "var1": "prod var1", "var2": "prod var2" }, "hw:dev": { "var1": `hw:dev ${var1}`, "var2": `hw:dev ${var2}` }, "hw:test": { "var1": "hw:test var1", "var2": "hw:test var2 }, "hw:prod": { "var1": "hw:prod var1", "var2": "hw:prod var2" } }
环境变量使用,与package.json的script命令中-e后面的环境对应,上面配置的为dev环境
let env = process.env; console.log('var1 ',env.var1); console.log('var2 ',env.var2);