由于跟着官方文档可能出现报错[plugin:vite:css] [sass] Module loop: this module is already
,于是写一份避坑指南。
1. 安装sass
基于vite的项目默认不支持css预处理器,需要开发者单独安装
npm i sass -D
2. 准备定制化的样式文件
/* 只需要重写你需要的即可 */
@forward 'element-plus/theme-chalk/src/common/var.scss' with ($colors: ('primary': (// 主色'base': #27ba9b,),'success': (// 成功色'base': #1dc779,),'warning': (// 警告色'base': #ffb302,),'danger': (// 危险色'base': #e26237,),'error': (// 错误色'base': #cf4444,),)
)
3. 自动导入配置
这里自动导入需要深入到elementPlus的组件中,按照官方的配置文档来
- 自动导入定制化样式文件进行样式覆盖
- 按需定制主题配置 (需要安装 unplugin-element-plus
npm i unplugin-element-plus
)
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),AutoImport({resolvers: [ElementPlusResolver()],}),Components({resolvers: [ElementPlusResolver({importStyle: "sass",})],}),// 按需定制主题配置ElementPlus({useSource: true,}),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},css: {preprocessorOptions: {scss: {// 自动导入定制化样式文件进行样式覆盖additionalData: `@use "@/styles/element/index.scss" as *;`,}}}
})
main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
const app = createApp(App)app.use(createPinia())
app.use(router)
app.use(ElementPlus)
app.mount('#app')