經常使用vue開源UI組件庫,如iview,Element,Vant等。於是自己嘗試借助vue-cli4搭建vue組件庫。如何搭建vue組件庫以及npm發布組件庫網上的軟文很多,就不詳細介紹搭建過程。在借鑒網上一些搭建過程中,發現大多數案例其實沒有實現組件的按需加載,有的樣式還需要手動按需引入;如何解決這個問題?
解決這個問題使用到了 babel-plugin-import 依賴,對於babel-plugin-import依賴的安裝與介紹詳見https://www.npmjs.com/package/babel-plugin-import
假設項目中要使用的組件:import { Switch } from "v-easyui123";
對於babel-plugin-import配置,按照介紹資料,babel.config.js配置多種情況如下:
配置一:{ "libraryName": "v-easyui123", style: "css" }應該等價於:
var switch = require('v-easyui123/lib/switch');
require('v-easyui123/lib/switch/style/css');
配置二:{ "libraryName": "v-easyui123", style: true } 應該等價於:
var switch = require('v-easyui123/lib/switch');
require('v-easyui123/lib/switch/style');
對於上面兩種配置,組件都能按需引入,但是對應組件的樣式即使更改成對應的解析路徑都不能引入成功,那么到底如何解決呢?
對於樣式的加載,官網上還有這么一段話:If option style is a Function, babel-plugin-import will auto import the file which filepath equal to the function return value. This is useful for the components library developers。
大概意思就是如果屬性style是一個函數,那么babel-plugin-import會自動導入函數返回值的文件,看v-easyui123依賴目錄:
對應的配置文件如下:
module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ], plugins: [ [ "import", { libraryName: "v-easyui123", style: (name) => { console.log('style-->>', name) // v-easyui123/lib/switch/index.js // 注意這里的name為組件所在的路徑,按需加載樣式配置提取對應組件名稱的css即可 return `v-easyui123/lib/style/${name.split('/')[2]}.css` }, customName: (name) => { console.log('customName-->>', name) //switch return `v-easyui123/lib/${name}/index.js` } } ] ] }
注意此配置中屬性style與customName函數中參數的含義
當項目中引入 import { Switch } from "v-easyui123";對於上面配置等價於:
var switch = require('v-easyui123/lib/switch');
require('v-easyui123/lib/switch/style/switch.css');
到此自定義組件庫樣式按需加載就搞定了