element-plus 按需导入中自动导入修改主题色

打包工具:webpack

一、根据element-plus官网给的方法配置自动导入 官网地址

1、首先你需要安装unplugin-vue-components 和 unplugin-auto-import这两款插件

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

2、配置vue.config.js

//vue.config.js

const { defineConfig } = require("@vue/cli-service");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");

module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    plugins: [
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      })
    ],
  },
});

二、配置主题 官网地址

1、通过使用scss变量配置主题。新建一个样式文件,用于修改 Element Plus 的样式变量,例如 css/variables.scss:

// css/variables.scss
/* 只需要重写你需要的即可 */
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
  $colors: (
    'primary': (
      'base': green,
    ),
    'success': (
      'base': red,
    ),
  ),
  $font-size:(
    'extra-large': 20px,
    'large': 18px,
    'medium': 16px,
    'base': 20px,
    'small': 13px,
    'extra-small': 12px,
  ),
  
);

2、配置vue.config.js

const { defineConfig } = require("@vue/cli-service");
const AutoImport = require("unplugin-auto-import/webpack");
const Components = require("unplugin-vue-components/webpack");
const { ElementPlusResolver } = require("unplugin-vue-components/resolvers");
const ElementPlus = require("unplugin-element-plus/webpack");

module.exports = defineConfig({
  css: {
    loaderOptions: {
      scss: {
        //自定义的主题文件
        additionalData: `@use "@/css/variables.scss" as *;`,
      },
    },
  },
  transpileDependencies: true,
  configureWebpack: {
    plugins: [
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: "sass" })], //importStyle配置样式引入方式,自动引入修改主题色设置此属性
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: "sass" })], //importStyle配置样式引入方式,自动引入修改主题色设置此属性
      }),
      ElementPlus({
        useSource: true,
      }),
    ],
  },
});

补充:importStyle可以配置element-plus的样式引入方式,它默认是css,利用scss变量修改主题时,需要将这个属性设置为scss

你可能感兴趣的:(vue.js,前端,javascript)