目录
安装 react-app-rewired 包后,在根目录创建 config-overrides.js 自定义配置,最后修改 package.json 中的 scripts(替换react-scripts为react-app-rewired)
// .env.development
REACT_APP_ENV=development
// .env.production
REACT_APP_ENV=production
"scripts": {
"start": "react-app-rewired start",
"build:dev": "dotenv -e .env.development react-app-rewired build",
"build:pro": "dotenv -e .env.production react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
"devDependencies": {
"dotenv-cli": "^2.0.1",
"react-app-rewired": "^2.1.3"
}
运行开发环境(npm start)、打包测试环境(npm run build:dev)、打包生产环境(npm run build:pro),分别 打印 process.env 如下:
// 1. 开发环境(npm start)
{NODE_ENV: "development", PUBLIC_URL: "", REACT_APP_ENV: "development"}
// 2. 测试环境(npm run build:dev)
{NODE_ENV: "production", PUBLIC_URL: "", REACT_APP_ENV: "development"}
// 3. 生产环境(npm run build:pro)
{NODE_ENV: "production", PUBLIC_URL: "", REACT_APP_ENV: "production"}