1.安装必要vite插件
yarn add vite-plugin-style-import -D
or
npm i vite-plugin-style-import -D
2.在vite.config.ts中进行配置
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import cesium from "vite-plugin-cesium"
import { resolve } from 'path'
import styleImport from 'vite-plugin-style-import'
export default defineConfig({
/**
* 在生产中服务时的基本公共路径。
* @default '/'
*/
base: "./",
resolve: {
alias: [
{
find: "@",
replacement: resolve(__dirname, "./src")
}
]
},
plugins: [
vue(),
cesium(),
styleImport({
libs: [{
libraryName: 'ant-design-vue',
esModule: true,
resolveStyle: (name) => {
return `ant-design-vue/es/${name}/style/css`;
},
}]
})
]
})
(如果是webpack的话需要在babel.config.js下添加plugins)
3.按需加载注册文件
创建一个新的文件夹存放注册文件
- register-antdv.ts
// 按需引入组件
import { App } from "vue";
import {
Button,
Input,
Layout,
Menu
} from 'ant-design-vue'
const components = [
Button,
Input,
Layout,
Menu
];
export default function (app: App): void {
for (const component of components) {
app.component(component.name, component);
}
}
- index.ts
import { App } from "vue";
import registerAntdv from "./register-antdv";
export function globalRegister(app: App): void {
app.use(registerAntdv);
}
4.挂载在main.ts中
import { createApp } from 'vue'
import App from './App.vue'
import router from './router';
import store from './store';
import { globalRegister } from "./global";
const app = createApp(App);
//注册ant-design-vue
app.use(globalRegister)
app.use(store);
app.use(router);
app.mount("#app");
此时再写入样式得时候就可以直接使用
<template>
<div>
<a-button type="primary"> Primary </a-button>
<a-button type="primary">123</a-button>
</div>
</template>
<script setup lang='ts'>
</script>
<style lang='less' scoped>
</style>