自定义Element Plus主题
前言
相比于 Antd 直接全局添加 theme 配置而言,ELement 自定义组件样式相对复杂。注册 ELement Plus 时,全量导入和按需导入的配置并不相同,本文一一介绍配置方式。
全量导入ElementPlus的处理方式
如果是如下这种全量导入 Element Plus
import App from "./App.vue"
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'const app = createApp(App)
app.use(ElementPlus)
创建 scss 文件,并在入口文件中导入即可
// styles/element/index.scss
/* 只需要重写你需要的即可 */
@forward 'element-plus/theme-chalk/src/common/var.scss' with ($colors: ('primary': ('base': green,),),
);// 导入所有样式:
@use "element-plus/theme-chalk/src/index.scss" as *;
import App from "./App.vue"
import ElementPlus from 'element-plus'
// import 'element-plus/dist/index.css'
// 引入自定义主题样式
import "./styles/element/index.scss"const app = createApp(App)
app.use(ElementPlus)
按需导入ElementPlus的处理方式
主要代码如下
import { defineConfig, loadEnv } from "vite"
import type { UserConfig, ConfigEnv } from "vite"
import vue from "@vitejs/plugin-vue"
import { resolve } from "path"
// 自动导入配置相关
import AutoImport from "unplugin-auto-import/vite"
import Components from "unplugin-vue-components/vite"
import { ElementPlusResolver } from "unplugin-vue-components/resolvers"
import Icons from "unplugin-icons/vite"
import IconsResolver from "unplugin-icons/resolver"export default defineConfig(({ mode }: ConfigEnv): UserConfig => {const config = loadEnv(mode, "./")return {plugins: [vue(),AutoImport({resolvers: [ElementPlusResolver(), IconsResolver()],imports: ["vue", "vue-router"],dts: "./src/types/auto-imports.d.ts",}),// 自动注册组件Components({resolvers: [ElementPlusResolver({ importStyle: "sass" }),IconsResolver({ enabledCollections: ["ep"] }),],dts: "./src/types/components.d.ts",}),// 自动安装图标Icons({compiler: "vue3", // 编译方式autoInstall: true,}),],css: {preprocessorOptions: {scss: {additionalData: `@use "./src/styles/variables.scss" as *; @use "./src/styles/element/common.scss" as *;`, // 全局变量 以及 Ele自定义主题 样式},},},}
})