From efbe9cb22a1d8b6df1782c4ca8f934d17ecd3e8a Mon Sep 17 00:00:00 2001 From: loicduong Date: Sun, 8 Sep 2024 12:08:21 +0700 Subject: [PATCH] feat(core): add runtime config --- index.html | 1 + public/runtime.config.js | 2 ++ src/locales/langs/en-us.ts | 2 +- src/utils/env.ts | 6 ++++-- src/utils/service.ts | 7 +++---- 5 files changed, 11 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 2f9582e..266c0a3 100644 --- a/index.html +++ b/index.html @@ -6,6 +6,7 @@ %VITE_APP_TITLE% +
diff --git a/public/runtime.config.js b/public/runtime.config.js index 60b67b2..e4eaae2 100644 --- a/public/runtime.config.js +++ b/public/runtime.config.js @@ -1,3 +1,5 @@ window.config = { VITE_BUILD_PREFIX: '', + VITE_SERVICE_BASE_URL: '', + VITE_OTHER_SERVICE_BASE_URL: '', } diff --git a/src/locales/langs/en-us.ts b/src/locales/langs/en-us.ts index 6bfbf53..7259caa 100644 --- a/src/locales/langs/en-us.ts +++ b/src/locales/langs/en-us.ts @@ -221,7 +221,7 @@ const local: App.I18n.Schema = { projectNews: { title: 'Project News', moreNews: 'More News', - desc1: 'Loic Duong created the open source project vue-naive-admin on May 28, 2021!', + desc1: 'Loic Duong created the open source project vue-naive-admin on May 28, 2024!', desc2: 'Loic Duong submitted a bug to vue-naive-admin, the multi-tab bar will not adapt.', desc3: 'Loic Duong is ready to do sufficient preparation for the release of vue-naive-admin!', desc4: 'Loic Duong is busy writing project documentation for vue-naive-admin!', diff --git a/src/utils/env.ts b/src/utils/env.ts index f40f57d..181dfc7 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -1,3 +1,5 @@ -export function getEnvVariable(name: Env.Runtime, env?: Env.ImportMeta): CommonType.NullableString { - return window.config?.[name] || (env ? env[name] : import.meta.env[name]) +export function getEnvVariable(name: Env.Runtime, env?: Env.ImportMeta): string { + return typeof window === 'undefined' + ? env?.[name] || import.meta.env[name] + : window.config?.[name] || env?.[name] || import.meta.env[name] } diff --git a/src/utils/service.ts b/src/utils/service.ts index b2b079e..33270d7 100644 --- a/src/utils/service.ts +++ b/src/utils/service.ts @@ -1,4 +1,5 @@ import json5 from 'json5' +import { getEnvVariable } from './env' /** * Create service config by current env @@ -6,18 +7,16 @@ import json5 from 'json5' * @param env The current env */ export function createServiceConfig(env: Env.ImportMeta) { - const { VITE_SERVICE_BASE_URL, VITE_OTHER_SERVICE_BASE_URL } = env - let other = {} as Record try { - other = json5.parse(VITE_OTHER_SERVICE_BASE_URL) + other = json5.parse(getEnvVariable('VITE_OTHER_SERVICE_BASE_URL', env)) } catch { console.error('VITE_OTHER_SERVICE_BASE_URL is not a valid json5 string') } const httpConfig: App.Service.SimpleServiceConfig = { - baseURL: VITE_SERVICE_BASE_URL, + baseURL: getEnvVariable('VITE_SERVICE_BASE_URL', env), other, }