React 项目分环境打包
(一) 在 package.json 文件中配置命令
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start:test": "set REACT_APP_MODE=test&& react-scripts start",
"start:stage": "set REACT_APP_MODE=stage&& react-scripts start",
"start:localhost": "set REACT_APP_MODE=localhost&& react-scripts start",
"build:dev": "set REACT_APP_MODE=development&& react-scripts build",
"build:pro": "set REACT_APP_MODE=production&& react-scripts build",
"eject": "react-scripts eject"
},
(二) 在 src 目录下新建一个文件夹 config 里面写几个文件(src 目录)
- api_development.js
let url = {
homeurl: 'www.development.com',
}
export default url
- api_localhost.js
let url = {
homeurl: 'www.localhost.com',
}
export default url
- api_production.js
let url = {
homeurl: 'www.production.com',
}
export default url
- api_stage.js
let url = {
homeurl: 'www.stage.com',
}
export default url
- api_test.js
let url = {
homeurl: 'www.test.com',
}
export default url
(三)在 src 目录下在新建一个 config.js 文件
- 里面写
import developmentapi from './config/api_development.js'
import productionapi from './config/api_production.js'
import testapi from './config/api_test.js'
import localhostapi from './config/api_localhost.js'
import stageapi from './config/api_stage.js'
let url
if (process.env.REACT_APP_MODE === 'development') {
console.log('开发环境')
url = developmentapi
} else if (process.env.REACT_APP_MODE === 'production') {
console.log('生产环境')
url = productionapi
} else if (process.env.REACT_APP_MODE === 'test') {
console.log('测试环境')
url = testapi
} else if (process.env.REACT_APP_MODE === 'localhost') {
console.log('localhost环境')
url = localhostapi
} else if (process.env.REACT_APP_MODE === 'stage') {
console.log('stage环境')
url = stageapi
}
export default url
(四) 在引用的页面直接引用 config.js 即可
import React, { Component, Fragment } from 'react'
import url from './config.js'
class App extends Component {
constructor(props) {
super(props)
this.state = {
message: '首页',
}
}
render() {
return (
<Fragment>
<div>{url.homeurl}</div>
</Fragment>
)
}
}
export default App
(五) 然后敲不同的命令来调用不同的接口
npm run start:test
npm run start:stage
npm run build:dev
.
.
.
还有第二种方法
(1)在项目的根目录新建 3 个文件对应的文件写下面的代码
// .env.development 开发的配置文件
REACT_APP_BASE_URL = 'https://xxxxx'
REACT_APP_ENV = 'development'
// .env.test 测试的配置文件
REACT_APP_BASE_URL = 'https://xxxxx'
REACT_APP_ENV = 'test'
// .env.production 生产的配置文件
REACT_APP_BASE_URL = 'https://xxxxx'
REACT_APP_ENV = 'production'
(2) 安装 cross-env
- cross-env 为了定义全平台兼容的环境命令
npm install cross-env -D
或
yarn add cross-env -D
(3) 在 package.json 的 scripts 里面添加代码
"start:dev": "cross-env REACT_APP_ENV=development react-app-rewired start",
"start:test": "cross-env REACT_APP_ENV=test react-app-rewired start",
"start:prod": "cross-env REACT_APP_ENV=production react-app-rewired start",
最后依据不同的抢矿使用不同的命令