1. 程式人生 > 其它 >vite ant Design vue按需載入

vite ant Design vue按需載入

vite ant Design vue按需載入

main.ts

import { createApp } from 'vue'
import { setupAntd } from './antd-ui'
import App from './App.vue'

const app = createApp(App)
setupAntd(app)
app.mount('#app')


antd-ui.ts

import {
  Button, Pagination, PageHeader, Select, Table, Layout, Menu, Form, Input, Spin,
  BackTop, Modal, message, Space, Breadcrumb, Popconfirm, Avatar, Skeleton
} from 'ant-design-vue';
const plugins = [Button, Pagination, PageHeader, Select, Table, Layout, Menu, Form, Input, Spin,
  BackTop, Modal, message, Space, Breadcrumb, Popconfirm, Avatar, Skeleton];

export const setupAntd = (app: any, options = {}) => {
  app.config.globalProperties.$mes = message;
  plugins.forEach((plugin) => {
    app.use(plugin);
  });
};

vite.config.ts

安裝 3個外掛

npm install less less-loader vite-plugin-style-import -D

由於 vite 本身已按需匯入了元件庫,因此僅樣式不是按需匯入的,因此只需按需匯入樣式即可。

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'

// 如果編輯器提示 path 模組找不到,則可以安裝一下

@types/node -> npm i @types/node -D

 import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src') // 設定 `@` 指向 `src` 目錄
    }
  },
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: 'ant-design-vue',
          esModule: true,
          resolveStyle: (name) => {
            return `ant-design-vue/es/${name}/style/index`
          }
        }
      ]
    }),
  ],

  css: {
    preprocessorOptions: {
      less: {
        modifyVars: { // 更改主題在這裡
          'primary-color': '#52c41a',
          'link-color': '#1DA57A',
          'border-radius-base': '2px'
        },
        javascriptEnabled: true
      }
    }
  }
  }
})

參考

https://blog.csdn.net/weixin_46602773/article/details/116048113