16

基于Vite+vue3+ant design的定制主题使用方式

 2 years ago
source link: https://www.joynop.com/p/454.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

近期在使用vitevue3.xant design3.x尝试搭建框架

在UI库配置的时候,尝试了如下几种方式进行定制主题(自定义主题)

本次使用库版本

"ant-design-vue": "^2.2.8",
"vite": "^2.8.4",
"less": "^4.1.2",
"less-loader": "^10.2.0",

安装ui库

yarn add ant-design-vue@next

采用vite按需加载方式

如果你使用的 Vite,你可以使用 unplugin-vue-components 来进行按需加载。但是此插件无法处理非组件模块,如 message,这种组件需要手动加载:

import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css'; //vite只能用 ant-design-vue/es 而非 ant-design-vue/lib
TypeScript

修改vite.config.ts

+ import Components from "unplugin-vue-components/vite";
+ import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";

 plugins: [
     ...otherPlugins,
+     Components({
+       resolvers: [AntDesignVueResolver({ importStyle: true })],
+     }),
+   ],
TypeScript

截止到此处ant.design ui已经可以正常使用了,为了丰富扩展主题,我们还需要作如下操作

安装less和less-loader

yarn add less
yarn add less-loader  --dev

这样,在*.vue就可使用less样式了,如

<style lang="less" scope>
.text {
 color:red;
}

继续在vite.config.ts中扩展

export default defineConfig({
  css: {
    // css预处理器
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        charset: false,
        modifyVars: {
          // "@primary-color": "red",
        },
      },
    },
  },
});
TypeScript

自定义主题

  1. 通过vite配置,进行主题定制

unplugin-vue-componentsAntDesignVueResolverimportStyle属性为true或者css时,如法进行自定义,需修改如下

AntDesignVueResolver({ importStyle: "less" })]

这样可以再vite.config.ts中通过设定modifyVars来达到自定义主题的目的,如

modifyVars: {
  "@primary-color": "red",
},
TypeScript
  1. 通过业务代码挂在less样式进行主题定制

unplugin-vue-componentsAntDesignVueResolverimportStyle属性为true或者css时,如法进行自定义,需修改如下

AntDesignVueResolver({ importStyle: "false" })]

app.vue中引入样式文件

<style lang="less">
@import "./assets/global.less";
</style>

global.less内容如下:

@import "ant-design-vue/dist/antd.less"; //引入样式antdesign官方样式文件
@primary-color: #00bd7e;// 自定义全局主色
@link-color: #000000; //自定义链接颜色

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK