element-plus的自動導入和按需導入方式詳解
element-plus根據(jù)官網(wǎng)文檔,推薦用戶采用按需導入的方式進行導入。
我的項目是使用vite進行構(gòu)建的,根據(jù)官網(wǎng)的文檔,利用unplugin-vue-components
插件進行自動按需導入。
當我們使用element的標簽時,無需再使用import對組件進行導入。
例如:
<el-button>test</el-button>
會自動引入ElButton組件。
不過當我們想要使用命令的方式創(chuàng)建element組件時,樣式會無法自動引入。
我們以ElMessage為例。
import { ElMessage } from 'element-plus' ElMessage.warning('warning')
如果不采用import的方式引入,會直接報錯:ElMessage沒有定義。所以這個import是省不了了。但是import了之后,消息彈窗是出來了,但是卻沒有樣式。這該怎么辦呢?
仔細閱讀文檔,我們可以發(fā)現(xiàn)在手動導入里,使用了一個叫unplugin-element-plus
的插件。該插件的官方文檔有詳細的使用說明,插件的主要功能如下:
import { ElButton } from 'element-plus' // ↓ ↓ ↓ ↓ ↓ ↓ import { ElButton } from 'element-plus' import 'element-plus/es/components/button/style/css'
我們可以看出,這個插件其實就是把你需要的組件的css或者sass文件自動引入進來,剛好彌補了上面的問題。
最后我們?nèi)缦屡渲庙椖浚?/p>
首先我們要安裝unplugin-vue-components
和unplugin-element-plus
。
npm i unplugin-vue-components unplugin-element-plus -D
之后配置一下vite.config.js文件。
import ElementPlus from 'unplugin-element-plus/vite' import Components from 'unplugin-vue-components/vite' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' export default defineConfig({ plugins: [ ElementPlus({ importStyle: 'sass', useSource: true }), Components({ resolvers: [ElementPlusResolver()] }) ] })
這樣配置之后,我們就可以享用element-plus的自動導入了。當然使用命令的組件還是需要你手動導入一下的。
補充:elementPlus圖標自動引入
首先安裝插件
npm i -D unplugin-icons unplugin-vue-components
下載圖標庫
npm i @element-plus/icons-vue
配置vite.config.js
import path from 'path' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import AutoImport from 'unplugin-auto-import/vite' import Components from 'unplugin-vue-components/vite' import Icons from 'unplugin-icons/vite' import IconsResolver from 'unplugin-icons/resolver' import { ElementPlusResolver } from 'unplugin-vue-components/resolvers' const pathSrc = path.resolve(__dirname, 'src') export default defineConfig({ esolve: { alias: { '@': pathSrc, }, }, plugins: [ vue(), AutoImport({ resolvers: [ ElementPlusResolver(), IconsResolver({ prefix: 'Icon', }), ], dts: path.resolve(pathSrc, 'auto-imports.d.ts'), }), Components({ resolvers: [ ElementPlusResolver(), IconsResolver({ enabledCollections: ['ep'], }) ], dts: path.resolve(pathSrc, 'components.d.ts'), }), Icons({ autoInstall: true, }), ] })
總結(jié)
到此這篇關(guān)于element-plus自動導入和按需導入的文章就介紹到這了,更多相關(guān)element-plus自動導入和按需導入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中this.$refs有值,但無法獲取ref的值問題及解決
這篇文章主要介紹了vue中this.$refs有值,但無法獲取ref的值問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01vue使用echarts實現(xiàn)柱狀圖動態(tài)排序效果
echarts在前端開發(fā)中實屬必不可缺的大數(shù)據(jù)可視化工具,這篇文章主要為大家詳細介紹了vue如何使用echarts實現(xiàn)柱狀圖動態(tài)排序效果,感興趣的可以了解下2023-10-10解決vue 使用setTimeout,離開當前路由setTimeout未銷毀的問題
這篇文章主要介紹了解決vue 使用setTimeout,離開當前路由setTimeout未銷毀的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07