根目录创建 package.json文件
{"name": "项目名称","version": "1.0.0","description": "","main": "main.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC","uni-app": {"scripts": {"uat-h5": {"title": "uat-h5","env": {"UNI_PLATFORM": "h5"},"define": {"UAT-ENV": true}},"prod-h5": {"title": "prod-h5","env": {"UNI_PLATFORM": "h5"},"define": {"PROD-ENV": true}},"dev-h5": {"title": "dev-h5","env": {"UNI_PLATFORM": "h5"},"define": {"dev-ENV": true}}}},"dependencies": {"qrcode": "^1.5.3"}
}
define为环境标识,建议大写
title为环境名,出现在打包列表
UNI_PLATFORM为打包平台
创建env.uat.ts、env.prod.ts、env.dev.ts文件
const env = {restHost:'http://43.139.56.173:8180', // apigameUrl:'http://43.139.56.173:8890', // 游戏url
}
export default {env
}
创建env.ts文件
import Prod from './env.prod'
import Uat from './env.uat'
import Dev from './env.dev'//api环境多的话 可以再创建文件引入//以下是uniapp判断不同环境引入不同配置文件
/* #ifdef UAT-ENV */
export const environment = Uat.env
/* #endif *//* #ifdef PROD-ENV */
export const environment = Prod.env
/* #endif *//* #ifndef UAT-ENV || PROD-ENV */
export const environment = Dev.env
/* #endif */
api封装文件引入env.ts文件 api封装时调用
import {environment} from '@/envList/env'
const request = (url,data,method) => {const token = uni.getStorageSync('token');let header = {Token: token,'Content-Type':'application/json; charset=utf-8'}return new Promise ((resolve,reject) => {uni.showLoading({title: "Loading..."});uni.request({url:environment.restHost+url,data:data,header:header,method:method,timeout: 30000,success(res) {uni.hideLoading();// token refreshif(res.header['new-token']) {uni.setStorageSync('token',res.header['new-token'])}if (res.data.code == 200) {resolve(res.data)}else{reject(res.data);uni.showToast({title: res.data.error.msg,icon:"error",duration:2000});}},fail(err) {reject(err);uni.showToast({title: 'error',icon:"error",duration:2000});},complete() {uni.hideLoading();}})})
}
class Http {get = function(url,data) {return request(url,data,'GET')}post = function(url,data) {return request(url,data,'POST')}
}
const http = new Http()
export default{http
}