本文共 1207 字,大约阅读时间需要 4 分钟。
在使用create-react-app搭建的项目中,实现不同环境(开发、测试、生产)的接口地址配置,可以通过以下步骤进行:
创建baseurl.js文件:在项目根目录下新建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;
配置.env文件:为每个环境创建相应的.env文件,并在文件中设置REACT_APP_ENV变量。例如:
REACT_APP_ENV=development
REACT_APP_ENV=test
REACT_APP_ENV=production
修改package.json脚本命令:在package.json中,确保每个构建命令加载正确的.env文件。例如:
{ "scripts": { "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:prod": "dotenv -e .env.production react-app-rewired build", "build:test": "dotenv -e .env.test react-app-rewired build" }}
使用dotenv-cli加载环境变量:确保在终端中使用以下命令运行构建任务:
npm run build:dev
npm run build:test
npm run build:prod
每次构建前,dotenv-cli会自动加载指定的.env文件,并将其内容加入到process.env中,使得BASE_URL能够根据不同环境获取正确的接口地址。
通过以上配置,您可以在不同的环境下,自动切换到适当的接口地址,简化了环境切换的工作流程。
转载地址:http://dead.baihongyu.com/