Vite+Vue3+ElementPlus change theme color

1. Install elementPlus and import it as needed

npm install element-plus --save

Install the two plugins unplugin-vue-components and unplugin-auto-import

npm install -D unplugin-vue-components unplugin-auto-import
// 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: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
})

In the case of on-demand import, customize the theme and use vite.  You can install and configure the unplugin-element-plus plugin for importing element-plus styles on demand 

npm i unplugin-element-plus -D
// 自动按需导入 element-plus 样式
import ElementPlus from 'unplugin-element-plus/vite'

export default defineConfig({
  // ...
  plugins: [
    // ...
    AutoImport({
      resolvers: [
        ElementPlusResolver({
          importStyle: 'sass',
        })
      ],
    }),
    Components({
      resolvers: [
        ElementPlusResolver({
          importStyle: 'sass',
      })
    ],
    }),
    ElementPlus({
      useSource: true,
    }),
  ],
})

 In ElementPlusResolver({ importStyle: 'sass' }), importStyle is required to configure the style import method, otherwise the custom theme will be invalid.

2. Create a new styles folder, create a new index.scss, and directly overwrite the Element Plus style variable:

@forward 'element-plus/theme-chalk/src/common/var.scss' with (
  $colors:(
    'white': #ffffff,
    'black': #000000,
    'primary': (
      'base': #17A7FF, // 修改primary base color
    ),
    'success': (
      'base': #67c23a,
    ),
    'warning': (
      'base': #e6a23c,
    ),
    'danger': (
      'base': #f56c6c,
    ),
    'error': (
      'base': #f56c6c,
    ),
    'info': (
      'base': #909399,
    ),
  ),
  $font-size:(
    'extra-large': 20px,
    'large': 18px,
    'medium': 16px,
    'base': 14px,
    'small': 13px,
    'extra-small': 12px,
  )
);

3. Introduce in vite.config.ts

export default defineConfig({
  // ...

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/index.scss" as *;`,
      },
    },
  },
})

Here you need to configure @, if you don’t configure @, an error will be reported.

Just re-run the project.

Guess you like

Origin blog.csdn.net/weixin_52020362/article/details/128315459