本文共 2449 字,大约阅读时间需要 8 分钟。
2019-03-27
什么是dotenv-cli,A global executable to run applications with the ENV variables loaded by dotenv
NPM
$ npm install -g dotenv-cli
Yarn
$ yarn global add dotenv-cli
$ dotenv
This will load the variables from the .env file in the current working directory and then run the command (using the new set of environment variables).
Another .env file could be specified using the -e flag:
$ dotenv -e .env2
Multiple .env files can be specified, and will be processed in order:
$ dotenv -e .env3 -e .env4
If you want to check the value of an environment variable, use the -p
flag
$ dotenv -p NODE_ENV
If you want to pass flags to the inner command use --
after all the flags to dotenv-cli
.
E.g. the following command without dotenv-cli:
mvn exec:java -Dexec.args="-g -f"
will become the following command with dotenv-cli:
$ dotenv -- mvn exec:java -Dexec.args="-g -f"
or in case the env file is at .my-env
$ dotenv -e .my-env -- mvn exec:java -Dexec.args="-g -f"
We support expanding env variables inside .env files (See npm package for more information)
For example:
IP=127.0.0.1PORT=1234APP_URL=http://${IP}:${PORT}
Using the above example .env
file, process.env.APP_URL
would be http://127.0.0.1:1234
.
项目中使用了create-react-app搭建的项目,package.json中用的react-app-rewired方式,由于webpack没有被释放,不能在webpack的配置文件直接配置适配,所以针对build 的dev,test, production环境取不同的接口地址,就不是很方便。(create-react-app默认情况下,webpack的配置是对dev ,production环境,并没有test。)
请求接口用的是axios,针对不同的环境设置不用baseurl即可, baseurl.js如下: let BASE_URL = ''; if(process.env.REACT_APP_ENV === 'development') { BASE_URL = 'http://开发环境/' } else if(process.env.REACT_APP_ENV === 'test'){ BASE_URL = 'http://测试环境/' } else if(process.env.REACT_APP_ENV === 'production'){ BASE_URL = 'http://生产环境/' }export default BASE_URL
剩余的问题就是如何得到process.env.REACT_APP_ENV 的值。方法是,不同的环境使用不同的build方式》dev 环境build 的话用npm run build:dev
prodution 环境build 的话 用npm run build:prodution test 环境build 的话 用npm run build:test
package.json文件简略如下:
"start": "dotenv -e .env.development react-app-rewired start ", "test": "react-app-rewired test", "eject": "react-scripts eject","build:dev": "dotenv -e .env.dev react-app-rewired build", "build:production": "dotenv -e .env.production react-app-rewired build", "build:test": "dotenv -e .env.test react-app-rewired build"
使用了 与 env文件
包的作用是可以使用.env文件指定的变量,然后process.env对象就有该变量的值了。 (dotenv使用方式) env文件可以按照如下方式: 例如在.env.development文件中: REACT_APP_ENV=development
转载地址:http://dead.baihongyu.com/