本篇文章將介紹如何使用 vite 打包我們的組件庫,同時(shí)告訴大家如何使用插件讓打包后的文件自動(dòng)生成聲明文件(*.d.ts)
打包配置
vite 專門提供了庫模式的打包方式,配置其實(shí)非常簡(jiǎn)單,首先全局安裝 vite 以及@vitejs/plugin-vue
pnpm add vite @vitejs/plugin-vue -D -w
在 components 文件下新建vite.config.ts配置文件
import { defineConfig } from “vite”;
import vue from “@vitejs/plugin-vue”;
export default defineConfig({
build: {
//打包后文件目錄
outDir: “es”,
//壓縮
minify: false,
rollupOptions: {
//忽略打包vue文件
external: [“vue”],
//input: [“index.ts”],
output: {
globals: {
vue: “Vue”,
},
dir: “dist”,
},
},
lib: {
entry: “./index.ts”,
name: “easyest”,
fileName: “easyest”,
formats: [“es”, “umd”, “cjs”],
},
},
plugins: [vue()],
});
然后在 components/package.json 添加打包命令scripts
“scripts”: {
“build”: “vite build”
},
執(zhí)行pnpm run build
同時(shí)生成了打包后的 dist 文件
但是這種打包方式最終會(huì)將整個(gè)組件庫打包到一個(gè)文件中,并且樣式文件也不能按需加載,所以我們需要修改一下配置讓打包后的結(jié)構(gòu)和我們開發(fā)的結(jié)構(gòu)一致,如下配置我們將打包后的文件放入 easyest 目錄下,因?yàn)楹罄m(xù)發(fā)布組件庫的名字就是 easyest,當(dāng)然這個(gè)命名大家可以隨意
import { defineConfig } from “vite”;
import vue from “@vitejs/plugin-vue”;
export default defineConfig({
build: {
//打包文件目錄
outDir: “es”,
//壓縮
//minify: false,
rollupOptions: {
//忽略打包vue文件
external: [“vue”],
input: [“index.ts”],
output: [
{
//打包格式
format: “es”,
//打包后文件名
entryFileNames: “[name].mjs”,
//讓打包目錄和我們目錄對(duì)應(yīng)
preserveModules: true,
exports: “named”,
//配置打包根目錄
dir: “…/easyest/es”,
},
{
//打包格式
format: “cjs”,
//打包后文件名
entryFileNames: “[name].js”,
//讓打包目錄和我們目錄對(duì)應(yīng)
preserveModules: true,
exports: “named”,
//配置打包根目錄
dir: “…/easyest/lib”,
},
],
},
lib: {
entry: “./index.ts”,
},
},
plugins: [vue()],
});
執(zhí)行pnpm run build,此時(shí)生成打包后的文件目錄如下
但是此時(shí)的所有樣式文件還是會(huì)統(tǒng)一打包到 style.css 中,還是不能進(jìn)行樣式的按需加載,所以接下來我們將讓 vite 不打包樣式文件,樣式文件后續(xù)單獨(dú)進(jìn)行打包。
聲明文件
到這里其實(shí)打包的組件庫只能給 js 項(xiàng)目使用,在 ts 項(xiàng)目下運(yùn)行會(huì)出現(xiàn)一些錯(cuò)誤,而且使用的時(shí)候還會(huì)失去代碼提示功能,這樣的話我們就失去了用 ts 開發(fā)組件庫的意義了。所以我們需要在打包的庫里加入聲明文件(.d.ts)。
安裝vite-plugin-dts,注意版本最好一致
pnpm add vite-plugin-dts@1.4.1 -D -w
在vite.config.ts引入,注意這里同時(shí)添加了組件命名插件DefineOptions(上篇文章提到過,注意這個(gè)要寫在dts后面,源碼中可能有誤)
import { defineConfig } from “vite”;
import vue from “@vitejs/plugin-vue”;
import dts from “vite-plugin-dts”;
import DefineOptions from “unplugin-vue-define-options/vite”;
export default defineConfig({
plugins: [
vue(),
dts({
entryRoot: “./src”,
outputDir: [“…/easyest/es/src”, “…/easyest/lib/src”],
//指定使用的tsconfig.json為我們整個(gè)項(xiàng)目根目錄下,如果不配置,你也可以在components下新建tsconfig.json
tsConfigFilePath: “…/…/tsconfig.json”,
}),
DefineOptions(),
],
});
再次打包就會(huì)發(fā)現(xiàn)打包后文件中出現(xiàn)了我們需要的聲明文件文章來源:http://www.zghlxwxcb.cn/news/detail-819518.html
其實(shí)現(xiàn)在大部分前端構(gòu)建腳手架都支持 esmodule 了,而 esmodule 本身就支持按需加載,所以說組件庫打包后的 es 格式它本身自帶 treeShaking,而不需要額外配置按需引入。后面我們要做的則是讓樣式文件也支持按需引入,敬請(qǐng)期待。文章來源地址http://www.zghlxwxcb.cn/news/detail-819518.html
到了這里,關(guān)于從0搭建Vue3組件庫(五): 如何使用Vite打包組件庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!