fix: When refreshing the page, the topic is wrong

This commit is contained in:
vben
2024-05-25 22:43:22 +08:00
parent 352119cc3a
commit f2644dbbc5
11 changed files with 38 additions and 24 deletions

View File

@@ -2,7 +2,7 @@ import type { UserConfig } from 'vite';
import { resolve } from 'node:path';
import { defineConfig, mergeConfig } from 'vite';
import { defineConfig, loadEnv, mergeConfig } from 'vite';
import { getApplicationConditionPlugins } from '../plugins';
import { getCommonConfig } from './common';
@@ -14,12 +14,13 @@ function defineApplicationConfig(options: DefineAppcationOptions = {}) {
const { appcation = {}, vite = {} } = options;
const root = process.cwd();
const isBuild = command === 'build';
// const env = loadEnv(mode, root);
const env = loadEnv(mode, root);
const plugins = await getApplicationConditionPlugins({
compress: false,
compressTypes: ['brotli', 'gzip'],
devtools: true,
env,
extraAppConfig: true,
html: true,
i18n: true,

View File

@@ -86,6 +86,7 @@ async function getApplicationConditionPlugins(
): Promise<PluginOption[]> {
// 单独取否则commonOptions拿不到
const isBuild = options.isBuild;
const env = options.env;
const {
compress,
@@ -123,7 +124,7 @@ async function getApplicationConditionPlugins(
},
{
condition: injectAppLoading,
plugins: async () => [await viteInjectAppLoadingPlugin()],
plugins: async () => [await viteInjectAppLoadingPlugin(isBuild, env)],
},
{
condition: isBuild && !!compress,

View File

@@ -8,8 +8,22 @@ import { type PluginOption } from 'vite';
* 用于生成将loading样式注入到项目中
* 为多app提供loading样式无需在每个 app -> index.html单独引入
*/
async function viteInjectAppLoadingPlugin(): Promise<PluginOption | undefined> {
async function viteInjectAppLoadingPlugin(
isBuild: string,
env: Record<string, any>,
): Promise<PluginOption | undefined> {
const loadingHtml = await getLoadingRawByHtmlTemplate();
const envRaw = isBuild ? 'prod' : 'dev';
const cacheName = `'__${env.VITE_APP_NAMESPACE}-${envRaw}-theme__'`;
// 获取缓存的主题
// 保证黑暗主题下刷新页面时loading也是黑暗主题
const injectScript = `
<script>
var theme = localStorage.getItem(${cacheName});
document.documentElement.classList.toggle('dark', theme === 'dark');
</script>
`;
if (!loadingHtml) {
return;
@@ -21,7 +35,10 @@ async function viteInjectAppLoadingPlugin(): Promise<PluginOption | undefined> {
transformIndexHtml: {
handler(html) {
const re = /<div\s*id\s*=\s*"app"\s*>(\s*)<\/div>/;
html = html.replace(re, `<div id="app">${loadingHtml}</div>`);
html = html.replace(
re,
`<div id="app">${injectScript}${loadingHtml}</div>`,
);
return html;
},
order: 'pre',

View File

@@ -5,7 +5,7 @@
}
.dark .loading {
background-color: #2c344a;
background-color: #0d0d10;
}
.dark .loading .title {

View File

@@ -18,7 +18,7 @@
}
.dark .loading {
background: #101827;
background: #0d0d10;
}
.title {

View File

@@ -39,6 +39,8 @@ interface ConditionPlugin {
interface CommonPluginOptions {
/** 是否开启devtools */
devtools?: boolean;
/** 环境变量 */
env: Record<string, any>;
/** 是否构建模式 */
isBuild?: boolean;
/** 构建模式 */