2023 vite+Element 按需加入和自定义主题 的 官方文档的补充版

官网的按需加入说的其实不太全,这里做一个汇总和补充

安装

pnpm install -D unplugin-vue-components unplugin-auto-import

创建文件

  • 新建一下路径的文件 src/styles/element/index.scss
  • 新建一下路径的文件 src/styles/element/dark.scss
  • $--colors:就可以自定义颜色了,如果还想自定义组件的样式可以查看文档
// src/styles/element/index.scss
// Custom Element style

$--colors: (
  "primary": (
    "base": green,
  ),
  "success": (
    "base": #21ba45,
  ),
  "warning": (
    "base": #f2711c,
  ),
  "danger": (
    "base": #db2828,
  ),
  "error": (
    "base": #db2828,
  ),
  "info": (
    "base": #42b8dd,
  ),
);

// if you want to import all
// @use 'element-plus/theme-chalk/src/index.scss' as *;

// You can comment it to hide debug info.
// @debug $--colors;

// You should use them in scss, because we calculate it by sass.
// comment next lines to use default color
@forward "element-plus/theme-chalk/src/common/var.scss" with (
  // do not use same name, it will override.
  $colors: $--colors
);

// custom dark variables
@use "./dark.scss" as *;

该文件是针对于 dark 暗黑模式的自定义样式

// src/styles/element/dark.scss
$--colors: (
  "primary": (
    "base": red,
  ),
);

@forward "element-plus/theme-chalk/src/dark/var.scss" with (
  $colors: $--colors
);

引入文件

vite.config.ts

import { defineConfig } from "vite";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import vue from "@vitejs/plugin-vue";
import path from "path";

const pathSrc = path.resolve(__dirname, "src");

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      "src/": `${pathSrc}/`,
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use 'src/styles/element/index.scss' as *;`,
      },
    },
  },
  plugins: [
    vue(),
    AutoImport({
      // global imports to register
      imports: ["vue", "vue-router"],
      resolvers: [ElementPlusResolver()],
      dts: "src/autoImport.d.ts",
    }),
    Components({
      // allow auto load markdown components under `./src/components/`
      extensions: ["vue", "md"],
      // allow auto import and register components used in markdown
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      resolvers: [
        ElementPlusResolver({
          importStyle: "sass",
        }),
      ],
      dts: "src/components.d.ts",
    }),
  ],
});

App.vue

注意,要在这里引入下 暗黑模式 的样式。

<style lang="scss">
  @use "element-plus/theme-chalk/src/dark/css-vars.scss" as *;
</style>
Licensed under CC BY-NC-SA 4.0
本博客已稳定运行
发表了53篇文章 · 总计28.17k字
使用 Hugo 构建
主题 StackJimmy 设计