进行联调的时候会有两套或者更多的环境,区分开发环境和生产环境来进行网络请求,这时候环境变量就起作用了
npm run serve
启动项目,发起开发环境(baseUrl为development.com)的网络请求npm run serve:pro
启动项目,发起生产环境(baseUrl为production.com)的网络请求npm run build:pro
打包项目放在生产环境,如果是自动化部署,这里应该修改Dockerfile文件里的配置,因为打包后的项目放在了dist/build/h5文件夹下了https://gitee.com/tang-yican/env-test
搭建教程地址:
https://uniapp.dcloud.net.cn/quickstart-cli.html#%E5%88%9B%E5%BB%BAuni-app
vue create -p dcloudio/uni-preset-vue env-test
package.json
里面的配置,把里面的scripts脚本代码改成如下配置: "scripts": {
"serve": "npm run serve:dev:h5",
"build": "npm run build:dev:h5",
"build:dev:h5": "cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-build",
"serve:dev:h5": "cross-env NODE_ENV=development UNI_PLATFORM=h5 vue-cli-service uni-serve",
"serve:pro": "npm run serve:pro:h5",
"build:pro": "npm run build:pro:h5",
"build:pro:h5": "cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-build",
"serve:pro:h5": "cross-env NODE_ENV=production UNI_PLATFORM=h5 vue-cli-service uni-serve"
},
// src/config/index.js
// 这个 NODE_ENV 就是环境变量
// 当用npm run serve启动项目时,NODE_ENV 为 development
// 当用npm run serve:pro启动项目时,NODE_ENV 为 production
const { NODE_ENV } = process.env;
const config = {
development: {
baseUrl: "https://development.com/api",
},
production: {
baseUrl: "https://production.com/api",
},
};
export default {
baseUrl: config[NODE_ENV].baseUrl,
shareUrl: config[NODE_ENV].shareUrl,
};
// src/utils/request.js
// 引入环境配置变量文件
import config from "../config/index.js";
const baseUrl = config.baseUrl;
function request(url, data = {}, method = "POST") {
const param = {
...data,
};
return new Promise((resolve, reject) => {
uni
.request({
url: `${baseUrl}${url}`,
header: {
"content-type": "application/x-www-form-urlencoded",
},
data: param,
method,
})
.then((res) => {
const result = res[1].data;
if (Number(result.code) === 200) {
resolve(result.data);
} else {
reject(result);
}
})
.catch((err) => {
uni.showToast({
title: "数据请求失败",
icon: "none",
duration: 2000,
});
});
});
}
export default request;
// src/pages/index/index.vue
<template>
<view class="content"> </view>
</template>
<script>
import request from "../../utils/request";
export default {
data() {
return {};
},
onLoad() {
this.testRequest();
},
methods: {
testRequest() {
request("testurl", {
testParam: 1,
});
},
},
};
</script>
<style>
</style>