1:react官方文档安装方法 使用 create-react-app 创建应用
npx create-react-app my-app
cd my-app
npm start
2:安装 cross-env 插件
yarn add cross-env
3:在src同级目录下新建 .env.development .env.production文件
图片如下
4:在 .env.development添加
REACT_APP_BASE_URL = 'http://127.0.0.5' //测试环境地址
REACT_APP_ENV = 'development
’
5:在 .env.production 添加
REACT_APP_BASE_URL = 'http://**' //生产环境地址
REACT_APP_ENV = 'production
6:打开 package.json 文件 找到 scripts:{}更改 注意 REACT_APP_ENV
"scripts": {
"start": "cross-env REACT_APP_ENV=development node scripts/start.js",
"build:pro": "cross-env REACT_APP_ENV=production node scripts/build.js",
"build:dev": "cross-env REACT_APP_ENV=development node scripts/build.js",
"test": "node scripts/test.js"
},
7:yarn run start 重新启动
8:在App.js文件 通过 process.env 查看
const baseUrl = process.env.REACT_APP_ENV === "production" ? process.env.REACT_APP_BASE_URL : 'http://127.0.0.5'
cosnole.log("baseUrl",baseUrl) // http://127.0.0.5
9:不同环境打包
1:打包测试环境 yarn build:dev
2:打包生产环境 yarn build:pro