Commit cb5e98f5 by zhuxichen

chore: update theme var

parent a7d0edf5
import path from 'path';
import fs from 'fs';
import less from 'less';
let currentTheme: Record<string, string> = {};
// 初始化主题
......@@ -7,7 +6,7 @@ export async function initializeTheme(themeMode: string = 'default') {
try {
const theme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
currentTheme = { ...theme };
refreshViteInjectedVariables(); // 刷新 Vite 变量
applyThemeVariables(); // 应用动态样式
console.log(`Initialized theme: ${themeMode}`);
} catch (error) {
console.error(`Failed to initialize theme: ${themeMode}`, error);
......@@ -19,49 +18,67 @@ export async function switchTheme(themeMode: string) {
try {
const newTheme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
currentTheme = { ...newTheme };
refreshViteInjectedVariables(); // 刷新 Vite 变量
applyThemeVariables(); // 应用动态样式
console.log(`Switched to theme: ${themeMode}`);
} 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) {
currentTheme[key] = value;
refreshViteInjectedVariables(); // 刷新 Vite 变量
applyThemeVariables(); // 应用动态样式
console.log(`Updated ${key} to ${value}`);
}
// 刷新 Vite 的动态变量注入
function refreshViteInjectedVariables() {
const lessContent = generateLessVariables(currentTheme);
const stylusContent = generateStylusVariables(currentTheme);
// 应用动态样式
function applyThemeVariables() {
// 应用到 Less
applyLessVariables();
fs.writeFileSync(
path.resolve(__dirname, '../styles/_generated-theme.less'), // 确保路径正确
lessContent,
);
fs.writeFileSync(
path.resolve(__dirname, '../styles/_generated-theme.styl'), // 确保路径正确
stylusContent,
// 应用到 Stylus
applyStylusVariables();
}
// 应用动态 Less 变量
function applyLessVariables() {
// 将当前主题变量转换为 Less 的格式
const lessVariables = Object.entries(currentTheme).reduce(
(acc, [key, value]) => ({ ...acc, [`@${key}`]: value }),
{},
);
if (import.meta.hot) {
import.meta.hot.invalidate(); // 触发 Vite 热更新
}
// 使用 Less.js 动态更新变量
less
.modifyVars(lessVariables)
.then(() => {
console.log('Less variables applied successfully:', lessVariables);
})
.catch((error) => {
console.error('Failed to apply Less variables:', error);
});
}
// 工具函数:生成 Less 变量
function generateLessVariables(theme: Record<string, string>) {
return Object.entries(theme)
.map(([key, value]) => `@${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`)
// 应用动态 Stylus 变量
function applyStylusVariables() {
const stylusVariables = Object.entries(currentTheme)
.map(([key, value]) => `$${key}: ${value};`)
.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>) {
return Object.entries(theme)
.map(([key, value]) => `$${key.replace(/([A-Z])/g, '-$1').toLowerCase()} = ${value}`)
.join('\n');
// 获取当前主题
export function getCurrentTheme() {
return { ...currentTheme };
}
declare module '*.module.css';
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>) {
.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) {
const themePath = path.resolve(__dirname, `src/styles/theme.${themeMode}.mjs`);
......@@ -44,9 +36,6 @@ export default defineConfig(async ({ mode }) => {
// 初始化主题
currentTheme = await loadTheme(themeMode);
// 生成全局样式文件
generateGlobalStyles(currentTheme);
return {
plugins: [
vue(),
......@@ -64,10 +53,10 @@ export default defineConfig(async ({ mode }) => {
preprocessorOptions: {
less: {
javascriptEnabled: true,
additionalData: `@import "${path.resolve(__dirname, 'src/styles/_generated-theme.less')}";`,
additionalData: generateLessVariables(currentTheme),
},
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