dotenv-cli

dotenv-cli

2019-03-27

dotenv-cli是什么

什么是dotenv-cli,A global executable to run applications with the ENV variables loaded by dotenv

dotenv-cli使用教程帮助文档

dotenv-cli

Installing

NPM

$ npm install -g dotenv-cli

Yarn

$ yarn global add dotenv-cli

Usage

$ dotenv <command with arguments>

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).

Custom .env files

Another .env file could be specified using the -e flag:

$ dotenv -e .env2 <command with arguments>

Multiple .env files can be specified, and will be processed in order:

$ dotenv -e .env3 -e .env4 <command with arguments>

Check env variable

If you want to check the value of an environment variable, use the -pflag

$ dotenv -p NODE_ENV

Flags to the underlying command

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"

Variable expansion

We support expanding env variables inside .env files (See dotenv-expandnpm package for more information)

For example:

IP=127.0.0.1
PORT=1234
APP_URL=http://${IP}:${PORT}

Using the above example .envfile, process.env.APP_URLwould 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"

使用了dotenv-cli 与  env文件
dotenv-cli包的作用是可以使用.env文件指定的变量,然后process.env对象就有该变量的值了。
(dotenv使用方式http://npm.taobao.org/package/dotenv-cli
env文件可以按照如下方式:
例如在.env.development文件中:
                REACT_APP_ENV=development

发布了270 篇原创文章 · 获赞 102 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/hahahhahahahha123456/article/details/103971040
CLI