Vite2 按需引入

Vite2 按需引入 Ant Design Vue 与 element-plus 还有 vant UI框架

这两个文档内按需引入这块,看不太懂于是在github issues上找了一下
目前为止比较好的解决办法,推荐第一种

第一种

注意⚠️有个问题:如果不引入所有组件的css,部分组件样式不全。
https://github.com/onebay/vite-plugin-imp
css也可以按需引入

# ./vite.config.js 文件

import vue from '@vitejs/plugin-vue'
import vitePluginImp from 'vite-plugin-imp'

/**
 * https://vitejs.dev/config/
 * @type {import('vite').UserConfig}
 */
export default {
    plugins: [
        vue(),
        vitePluginImp({
            libList: [
                {
                    libName: 'vant',
                    style(name) {
                        if (/CompWithoutStyleFile/i.test(name)) {
                            // This will not import any style file
                            return false
                        }
                        return `vant/es/${name}/index.css`
                    }
                },
                {
                    libName: 'ant-design-vue',
                    style(name) {
                        if (/popconfirm/.test(name)) {
                            // support multiple style file path to import
                            return [
                                'ant-design-vue/es/button/style/index.css',
                                'ant-design-vue/es/popover/style/index.css'
                            ]
                        }
                        return `ant-design-vue/es/${name}/style/index.css`
                    }
                },
                {
                    libName: 'element-plus',
                    style: (name) => {
                        return `element-plus/lib/theme-chalk/${name}.css`
                    }
                }
            ]
        })]
}
# ./src/main.js 文件
import { createApp } from 'vue'
import App from './App.vue'

import { Button } from 'ant-design-vue';

const app = createApp(App);

const antd = [
    Button,
]
antd.forEach(plugin => {
    app.use(plugin)
})

app.use(Button);
app.mount('#app')

图片alt

第二种

css不会按需引入
https://github.com/wingsico/vite-babel-plugin

引入button

图片alt

全量引入

图片alt

posted @ 2021-04-02 00:14  kousum  阅读(1838)  评论(4编辑  收藏  举报