黑暗主题
介绍
项目已经内置了黑暗主题切换,只需配置自己需要的颜色变量,即可在项目中使用
原理
通过 @trinapower/vite-plugin-theme 插件,将所有的颜色变量抽取到独立的 css 文件,并且全部在 html 上面加上 css 选择器。通过改变 html 标签的 data-theme 属性来进行黑暗主题切换
配置
黑暗主题颜色配置通过 @trinapower/vite-plugin-theme 实现,具体代码在 build/vite/plugin/theme
import { generateModifyVars } from '../../generate/generateModifyVars'
antdDarkThemePlugin({ preloadFiles: [ path.resolve(process.cwd(), 'node_modules/cosine-fee/dist/cosine-fee.less'), path.resolve(process.cwd(), 'src/design/index.less'), ], filter: (id) => (isBuild ? !id.endsWith('cosine-fee.less') : true), darkModifyVars: { ...generateModifyVars(true), 'text-color': '#c9d1d9', 'primary-1': 'rgb(255 255 255 / 8%)', 'text-color-base': '#c9d1d9', 'component-background': '#151515', 'heading-color': 'rgb(255 255 255 / 65%)', 'text-color-secondary': '#8b949e', 'border-color-base': '#303030', 'item-active-bg': '#111b26', 'app-content-background': '#1e1e1e', 'tree-node-selected-bg': '#11263c',
'alert-success-border-color': '#274916', 'alert-success-bg-color': '#162312', 'alert-success-icon-color': '#49aa19', 'alert-info-border-color': '#153450', 'alert-info-bg-color': '#111b26', 'alert-info-icon-color': '#177ddc', 'alert-warning-border-color': '#594214', 'alert-warning-bg-color': '#2b2111', 'alert-warning-icon-color': '#d89614', 'alert-error-border-color': '#58181c', 'alert-error-bg-color': '#2a1215', 'alert-error-icon-color': '#a61d24', }, }),切换
只需要使用 @trinapower/vite-plugin-theme 提供的函数来进行切换即可
import { darkCssIsReady, loadDarkThemeCss } from '@trinapower/vite-plugin-theme/es/client'import { addClass, hasClass, removeClass } from '@/utils/domUtils'
export async function updateDarkTheme(mode = 'light') { const htmlRoot = document.getElementById('htmlRoot') if (!htmlRoot) { return } const hasDarkClass = hasClass(htmlRoot, 'dark') if (mode === 'dark') { if (import.meta.env.PROD && !darkCssIsReady) { await loadDarkThemeCss() } htmlRoot.setAttribute('data-theme', 'dark') if (!hasDarkClass) { addClass(htmlRoot, 'dark') } } else { htmlRoot.setAttribute('data-theme', 'light') if (hasDarkClass) { removeClass(htmlRoot, 'dark') } }}