feat: 新增 VITE_USE_MOCK 配置

This commit is contained in:
h_mo 2023-04-10 10:36:43 +08:00
parent 71dc6a3374
commit ac3b3adec7
5 changed files with 24 additions and 3 deletions

View File

@ -1,6 +1,9 @@
# 运行环境
VITE_ENV = development
# 是否使用模拟数据
VITE_USE_MOCK = true
VITE_PORT = 3000
# BASE_URL

View File

@ -1,7 +1,12 @@
# 运行环境
VITE_ENV = production
# 是否使用模拟数据
VITE_USE_MOCK = true
# api域名
VITE_BASE_URL = /api/v1
# 上传域名
VITE_UPLOAD_URL = /upload

1
src/types/env.d.ts vendored
View File

@ -14,6 +14,7 @@ interface ImportMetaEnv {
readonly VITE_UPLOAD_URL: string;
readonly VITE_APP_CACHE_PREFIX: string;
readonly VITE_PORT: number;
readonly VITE_USE_MOCK: string;
}
interface ImportMeta {

View File

@ -34,7 +34,8 @@ export function getEnvMode(): string {
* @example:
*/
export function getEnvValue<T = string>(key: keyof ImportMetaEnv): T {
return import.meta.env[key] as unknown as T;
const envValue = import.meta.env[key];
return (envValue === 'true' ? true : envValue === 'false' ? false : envValue) as unknown as T;
}
/**
@ -55,6 +56,15 @@ export function isProdMode(): boolean {
return getEnvMode() === prodMode;
}
/**
* @description: Whether to use mock data
* @returns:
* @example:
*/
export function isUseMock(): boolean {
return getEnvValue('VITE_USE_MOCK');
}
/**
* @description: Get environment VITE_BASE_URL value
* @returns:

View File

@ -1,6 +1,6 @@
import { createAlova } from 'alova';
import AdapterUniapp from '@alova/adapter-uniapp';
import { getBaseUrl, isDevMode } from '@/utils/env';
import { getBaseUrl, isUseMock } from '@/utils/env';
import { mockAdapter } from '@/mock';
import { assign } from 'lodash-es';
import { useAuthStore } from '@/state/modules/auth';
@ -23,7 +23,9 @@ const HEADER = {
const alovaInstance = createAlova({
baseURL: BASE_URL,
...AdapterUniapp({
mockRequest: isDevMode() ? mockAdapter : undefined,
/* #ifndef APP-PLUS */
mockRequest: isUseMock() ? mockAdapter : undefined, // APP 平台无法使用mock
/* #endif */
}),
timeout: 5000,
beforeRequest: (method) => {