Commit cb5e98f5 by zhuxichen

chore: update theme var

parent a7d0edf5
import path from 'path'; import less from 'less';
import fs from 'fs';
let currentTheme: Record<string, string> = {}; let currentTheme: Record<string, string> = {};
// 初始化主题 // 初始化主题
...@@ -7,7 +6,7 @@ export async function initializeTheme(themeMode: string = 'default') { ...@@ -7,7 +6,7 @@ export async function initializeTheme(themeMode: string = 'default') {
try { try {
const theme = (await import(`@/styles/theme.${themeMode}.mjs`)).default; const theme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
currentTheme = { ...theme }; currentTheme = { ...theme };
refreshViteInjectedVariables(); // 刷新 Vite 变量 applyThemeVariables(); // 应用动态样式
console.log(`Initialized theme: ${themeMode}`); console.log(`Initialized theme: ${themeMode}`);
} catch (error) { } catch (error) {
console.error(`Failed to initialize theme: ${themeMode}`, error); console.error(`Failed to initialize theme: ${themeMode}`, error);
...@@ -19,49 +18,67 @@ export async function switchTheme(themeMode: string) { ...@@ -19,49 +18,67 @@ export async function switchTheme(themeMode: string) {
try { try {
const newTheme = (await import(`@/styles/theme.${themeMode}.mjs`)).default; const newTheme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
currentTheme = { ...newTheme }; currentTheme = { ...newTheme };
refreshViteInjectedVariables(); // 刷新 Vite 变量 applyThemeVariables(); // 应用动态样式
console.log(`Switched to theme: ${themeMode}`); console.log(`Switched to theme: ${themeMode}`);
} catch (error) { } catch (error) {
console.error(`Failed to switch theme to ${themeMode}:`, error); console.error(`Failed to switch theme: ${themeMode}`, error);
} }
} }
// 更新单个主题变量 // 动态更新单个主题变量
export function updateThemeVariable(key: string, value: string) { export function updateThemeVariable(key: string, value: string) {
currentTheme[key] = value; currentTheme[key] = value;
refreshViteInjectedVariables(); // 刷新 Vite 变量 applyThemeVariables(); // 应用动态样式
console.log(`Updated ${key} to ${value}`); console.log(`Updated ${key} to ${value}`);
} }
// 刷新 Vite 的动态变量注入 // 应用动态样式
function refreshViteInjectedVariables() { function applyThemeVariables() {
const lessContent = generateLessVariables(currentTheme); // 应用到 Less
const stylusContent = generateStylusVariables(currentTheme); applyLessVariables();
fs.writeFileSync( // 应用到 Stylus
path.resolve(__dirname, '../styles/_generated-theme.less'), // 确保路径正确 applyStylusVariables();
lessContent, }
);
fs.writeFileSync( // 应用动态 Less 变量
path.resolve(__dirname, '../styles/_generated-theme.styl'), // 确保路径正确 function applyLessVariables() {
stylusContent, // 将当前主题变量转换为 Less 的格式
const lessVariables = Object.entries(currentTheme).reduce(
(acc, [key, value]) => ({ ...acc, [`@${key}`]: value }),
{},
); );
if (import.meta.hot) { // 使用 Less.js 动态更新变量
import.meta.hot.invalidate(); // 触发 Vite 热更新 less
} .modifyVars(lessVariables)
.then(() => {
console.log('Less variables applied successfully:', lessVariables);
})
.catch((error) => {
console.error('Failed to apply Less variables:', error);
});
} }
// 应用动态 Stylus 变量
// 工具函数:生成 Less 变量 function applyStylusVariables() {
function generateLessVariables(theme: Record<string, string>) { const stylusVariables = Object.entries(currentTheme)
return Object.entries(theme) .map(([key, value]) => `$${key}: ${value};`)
.map(([key, value]) => `@${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`)
.join('\n'); .join('\n');
const existingStyleElement = document.getElementById('dynamic-stylus-styles');
if (existingStyleElement) {
existingStyleElement.remove();
}
const styleElement = document.createElement('style');
styleElement.id = 'dynamic-stylus-styles';
styleElement.textContent = stylusVariables;
document.head.appendChild(styleElement);
console.log('Stylus variables applied successfully.');
} }
// 工具函数:生成 Stylus 变量 // 获取当前主题
function generateStylusVariables(theme: Record<string, string>) { export function getCurrentTheme() {
return Object.entries(theme) return { ...currentTheme };
.map(([key, value]) => `$${key.replace(/([A-Z])/g, '-$1').toLowerCase()} = ${value}`)
.join('\n');
} }
declare module '*.module.css'; declare module '*.module.css';
declare module '*.module.less'; declare module '*.module.less';
declare module 'less' {
interface ModifyVars {
[key: string]: string;
}
interface LessStatic {
modifyVars(vars: ModifyVars): Promise<void>;
}
const less: LessStatic;
export default less;
}
...@@ -22,14 +22,6 @@ function generateStylusVariables(theme: Record<string, string>) { ...@@ -22,14 +22,6 @@ function generateStylusVariables(theme: Record<string, string>) {
.join('\n'); .join('\n');
} }
// 生成全局样式文件
function generateGlobalStyles(theme: Record<string, string>) {
const lessContent = generateLessVariables(theme);
const stylusContent = generateStylusVariables(theme);
fs.writeFileSync(path.resolve(__dirname, 'src/styles/_generated-theme.less'), lessContent);
fs.writeFileSync(path.resolve(__dirname, 'src/styles/_generated-theme.styl'), stylusContent);
}
// 动态加载主题文件 // 动态加载主题文件
async function loadTheme(themeMode: string) { async function loadTheme(themeMode: string) {
const themePath = path.resolve(__dirname, `src/styles/theme.${themeMode}.mjs`); const themePath = path.resolve(__dirname, `src/styles/theme.${themeMode}.mjs`);
...@@ -44,9 +36,6 @@ export default defineConfig(async ({ mode }) => { ...@@ -44,9 +36,6 @@ export default defineConfig(async ({ mode }) => {
// 初始化主题 // 初始化主题
currentTheme = await loadTheme(themeMode); currentTheme = await loadTheme(themeMode);
// 生成全局样式文件
generateGlobalStyles(currentTheme);
return { return {
plugins: [ plugins: [
vue(), vue(),
...@@ -64,10 +53,10 @@ export default defineConfig(async ({ mode }) => { ...@@ -64,10 +53,10 @@ export default defineConfig(async ({ mode }) => {
preprocessorOptions: { preprocessorOptions: {
less: { less: {
javascriptEnabled: true, javascriptEnabled: true,
additionalData: `@import "${path.resolve(__dirname, 'src/styles/_generated-theme.less')}";`, additionalData: generateLessVariables(currentTheme),
}, },
stylus: { stylus: {
additionalData: `@import "${path.resolve(__dirname, 'src/styles/_generated-theme.styl')}";`, additionalData: generateStylusVariables(currentTheme),
}, },
}, },
}, },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment