Vite + Element-plus项目实现自定义主题颜色

157 阅读1分钟

Element-plus默认主题色是蓝色,如何全局修改项目组件库的主题色?本文介绍了如何通过scss变量对主题色进行重写。

重写原有的scss变量

在src文件夹下创建element/index.scss,使用@forward用来转发"element-plus/theme-chalk/src/common/var.scss"模块,并用with对该模块中某些变量进行重写。

// index.scss
// 只需要重写你需要的即可
@forward "element-plus/theme-chalk/src/common/var.scss" with (
  $colors: (
    "primary": (
      "base": #323233,
    ),
    "hover": #fff,
  ),
  $button: (
    "hover-bg-color": #3f3f40,
    "hover-text-color": #fff,
  )
);
// 导入原有样式,@use是在@forward之后,它确保了在引用或使用被重写后的变量时,全局样式规则能够生效
@use "element-plus/theme-chalk/src/index.scss" as *;

如果需要针对性的对某个组件样式进行特定修改,参考源代码var.scss中声明的变量。

修改 main.ts

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'// 应用默认的 Element Plus 的样式
import '@/styles/element/index.scss'// 自定义样式需要在全局引入的样式后,才能进行覆盖

const app = createApp(App)
app.use(router)
app.use(ElementPlus)

app.use(router).use(pinia).use(ElementPlus).mount('#app')

修改 vite.config.ts

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    // 自动导入 Vue 组合 API
    AutoImport({
      resolvers: [ElementPlusResolver({
        // 如果不设置 importStyle: "sass",一些组件(如 ElMessage)可能会恢复为默认样式,因为它们的样式会从预编译的 CSS 中应用
        importStyle: "sass",
      })],
    }),
    // 自动导入对应的 Vue 组件
    Components({
      resolvers: [ElementPlusResolver({
        importStyle: "sass",
      })],
    }),
  ],
  css: {
    preprocessorOptions: {
      scss: {
        // 解决与 Sass 的 JavaScript API 相关的弃用警告:Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.
        api:'modern'
      },
    },
  },
});

总结

使用以上配置即可对使用了Element-Plus的项目进行默认主题色的重写。