第一步
在项目根目录中找到package.json文件,配置如下:
"scripts": {
"serve": "vue-cli-service serve --open",
"build": "vue-cli-service build",
"stage": "vue-cli-service build --mode staging"
},
第二步
在项目根目录中创建.env.development; .env.production; .env.staging;三个文件如下:
.env.development
文件 本地环境
MODE_ENV = 'development'
#must start with VUE_APP_
VUE_APP_ENV = 'development'
.env.production
文件 开发环境
NODE_ENV = 'production'
#must start with VUE_APP_
VUE_APP_ENV = 'production'
.env.staging
文件 测试环境
NODE_ENV = 'production'
#must start with VUE_APP_
VUE_APP_ENV = 'staging'
第三步
在src文件下创建config文件夹,在config文件夹下创建env.development.js,env.production.js,env.staging.js,index.js四个文件目录如下:
在env.development.js文件中配置如下:
// 本地环境配置
module.exports = {
title: '开发环境',
baseUrl: 'http://127.0.0.1:8888/api/private/v1/', // 项目地址
baseApi: 'https://test.xxx.com/api', // 本地api请求地址,注意:如果你使用了代理,请设置成'/'
APPID: 'xxx',
APPSECRET: 'xxx',
$cdn: 'https://gimg2.baidu.com'
}
在index.js文件中配置如下:
// 根据环境引入不同配置 process.env.VUE_APP_ENV
const environment = process.env.VUE_APP_ENV || 'production'
const config = require('./env.' + environment)
module.exports = config
第四步
在需要使用的组件中引入 如下:
// 根据环境不同引入不同api地址,需要配置后使用
import { baseUrl } from '@/config'
const service = axios.create({
baseURL: baseUrl, // 配置axios基地址
//withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})