Skip to content

Commit

Permalink
feat: 4-13 运行时环境
Browse files Browse the repository at this point in the history
  • Loading branch information
dL-hx committed Jan 14, 2024
1 parent 2dc05ff commit 61b1583
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 6 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="en">
<html lang="en" data-env="stg">

<head>
<meta charset="UTF-8" />
Expand Down
48 changes: 48 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* 运行时:判断环境变量
* 环境配置封装
*/

type ENV = 'dev' | 'stg' | 'prd'

// let env: ENV = 'dev'
// if (location.host.indexOf('localhost') > -1) {
// env = 'dev'
// } else if (location.host === 'driver-stg.marsview.cc') {
// env = 'stg'
// } else {
// env = 'prd'
// }

// 运行时候环境获取, 在html元素根元素上注入该元素, 通过下面方式获取当前环境
// <html lang="en" data-env="stg">
const env = (document.documentElement.dataset.env as ENV) || 'stg'

const config = {
dev: {
baseApi: '/api',
uploadApi: 'http://api-driver-dev.marsview.cc',
cdn: 'http://xxx.aliyun.com',
mock: false,
mockApi: 'https://www.fastmock.site/mock/5841b82d5672783b6fd62bb2a06aeb1f/api'
},
stg: {
baseApi: '/api',
uploadApi: 'http://api-driver-stg.marsview.cc',
cdn: 'http://xxx.aliyun.com',
mock: false,
mockApi: 'https://www.fastmock.site/mock/5841b82d5672783b6fd62bb2a06aeb1f/api'
},
prd: {
baseApi: '/api',
uploadApi: 'http://api-driver.marsview.cc',
cdn: 'http://xxx.aliyun.com',
mock: false,
mockApi: 'https://www.fastmock.site/mock/5841b82d5672783b6fd62bb2a06aeb1f/api'
}
}

export default {
env,
...config['prd']
}
22 changes: 17 additions & 5 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { message } from 'antd'
import axios, { AxiosError } from 'axios'
import { hideLoading, showLoading } from './loading/index.'
import storage from './storage'
import env from '@/config'

// 创建实例对象
const instance = axios.create({
// baseURL: '/api',
baseURL: import.meta.env.VITE_BASE_API,
// baseURL: import.meta.env.VITE_BASE_API,
baseURL: env.baseApi,
timeout: 8000,
timeoutErrorMessage: '请求超时, 请稍后再试',
withCredentials: true,
Expand All @@ -23,11 +25,21 @@ instance.interceptors.request.use(
// if (token) {
// config.headers.Authorization = 'Bearer ' + token
// }

// 配置环境变量的两种方式
// 当MOCK 开关打开时, 使用MOCK地址。 否则使用默认地址
if (import.meta.env.VITE_MOCK === 'true') {
config.baseURL = import.meta.env.VITE_MOCK_API
}else{
config.baseURL = import.meta.env.VITE_BASE_API
// 编译时环境
// if (import.meta.env.VITE_MOCK === 'true') {
// config.baseURL = import.meta.env.VITE_MOCK_API
// }else{
// config.baseURL = import.meta.env.VITE_BASE_API
// }

// 运行时环境
if (env.mock) {
config.baseURL = env.mockApi
} else {
config.baseURL = env.baseApi
}
return {
...config
Expand Down

0 comments on commit 61b1583

Please sign in to comment.