如何製作一個vue組件庫

如何製作一個vue組件庫

前言

在做開發的時候偶爾會做一些小型工具,在構建項目的時候不想引入一個龐大的組件庫。只想按需加載自己需要的組件。


採用了Element-ui的組件庫,發現它可以實現按需加載,因此對他進行了淺入的剖析。


他採用了一個babel-plugin-component插件,簡單的看下他的簡介

	//Example
	//Converts
	import { Button } from 'components'
	to
	
	var button = require('components/lib/button')
	require('components/lib/button/style.css')
Component directory structure
- lib // 'libDir'
  - index.js // or custom 'root' relative path
  - style.css // or custom 'style' relative path
  - componentA
    - index.js
    - style.css
  - componentB
    - index.js
    - style.css

對此我們可以分析他的功能就是將ES6模塊轉換爲CommonJs模塊採用node的CommonJs來加載所需要的文件,引入模塊。

所以可以總結這個插件其實就是你將項目打包成他所需要的目錄格式,他在根據自己編寫的轉換方式去加載,理解了這點我們就可以依葫蘆畫瓢了


現在所需要解決的是如何將組件庫打包成他所需的項目目錄

仿ElementUI構建自己的Vue組件庫用babel-plugin-component按需加載組件及自定義SASS主題 這是一個簡單的不想Element-ui一樣比較全面的庫,可以參考。

解析element-ui代碼庫

在package.json中發現了

'scripts':{
"dist": "npm run clean && npm run build:file && npm run lint && webpack --config build/webpack.conf.js && webpack --config build/webpack.common.js && webpack --config build/webpack.component.js && npm run build:utils && npm run build:umd && npm run build:theme"
}

執行該命令發現 重新打包了一份lib組件庫,因此可以從這個命令來分析 打包的全過程。

其中 build/webpack.component.js大概就是最基本的打包組件入口

執行腳本
npx webpack --config ./build/webpack.component.js
發現所有的組件打包到lib中 就是需要這樣的效果

vue-cli3腳手架打包lib

 npx vue-cli-service build --target lib --name builddemo --dest lib  package/index.js 

https://cli.vuejs.org/zh/guide/build-targets.html#%E5%BA%93
Vuejs 使用 lib 庫模式打包 umd 解決 NPM 包發佈的問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章