ruoyi-plus-vben5/internal/vite-config/src/plugins/inject-app-loading/index.ts

62 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-05-19 21:20:42 +08:00
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { fs } from '@vben/node-utils';
2024-06-08 19:49:06 +08:00
2024-05-19 21:20:42 +08:00
import { type PluginOption } from 'vite';
/**
* loading样式注入到项目中
* app提供loading样式 app -> index.html单独引入
*/
async function viteInjectAppLoadingPlugin(
isBuild: string,
env: Record<string, any>,
): Promise<PluginOption | undefined> {
2024-05-19 21:20:42 +08:00
const loadingHtml = await getLoadingRawByHtmlTemplate();
const envRaw = isBuild ? 'prod' : 'dev';
const cacheName = `'${env.VITE_APP_NAMESPACE}-${envRaw}-preferences-theme'`;
// 获取缓存的主题
// 保证黑暗主题下刷新页面时loading也是黑暗主题
const injectScript = `
<script data-app-loading="inject-js">
var theme = localStorage.getItem(${cacheName});
document.documentElement.classList.toggle('dark', /dark/.test(theme));
</script>
`;
2024-05-19 21:20:42 +08:00
if (!loadingHtml) {
return;
}
return {
enforce: 'pre',
name: 'vite:inject-app-loading',
transformIndexHtml: {
handler(html) {
const re = /<body\s*>/;
html = html.replace(re, `<body>${injectScript}${loadingHtml}`);
2024-05-19 21:20:42 +08:00
return html;
},
order: 'pre',
},
};
}
/**
* loading的html模板
*/
async function getLoadingRawByHtmlTemplate() {
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const loadingPath = join(__dirname, './loading.html');
if (!fs.existsSync(loadingPath)) {
return;
}
const htmlRaw = await fs.readFile(loadingPath, 'utf8');
return htmlRaw;
}
export { viteInjectAppLoadingPlugin };