Front-end engineering environment variable is typically used in cross-env set of scripts in package.json
"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" }
Such set environment variables, has the following disadvantages:
1. scripts command is too long, the writing is not convenient
2. confounding variables in a row, convenient viewing
3. Environment Variables introduction of multi-environment, we need to add a number of additional commands
For example: 1 in the environment and the environment 2 each have the development, production and test, to add the following
"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 is recommended to use this component to set environment variables, in one environment file, simple and convenient, multi-environment written especially convenient.
"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" } }
Environment variables, and the script command package.json -e environment corresponding to the latter, is arranged above the environmental dev
let env = process.env; console.log('env1 ',env.ENV1); console.log('env2 ',env.ENV2);