Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

這篇文章主要介紹“Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載”文章能幫助大家解決問題。

創(chuàng)新互聯(lián)公司成立與2013年,先為東遼等服務(wù)建站,東遼等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為東遼企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

使用 glup 打包組件庫并實(shí)現(xiàn)按需加載

當(dāng)我們使用 Vite 庫模式打包的時(shí)候,vite 會(huì)將樣式文件全部打包到同一個(gè)文件中,這樣的話我們每次都要全量引入所有樣式文件做不到按需引入的效果。所以打包的時(shí)候我們可以不讓 vite 打包樣式文件,樣式文件將使用 gulp 進(jìn)行打包。

自動(dòng)按需引入插件

現(xiàn)在很多組件庫的按需引入都是借助插件來解決的,比如ElementPlus是使用unplugin-vue-componentsunplugin-auto-import,這兩個(gè)插件可以實(shí)現(xiàn)

import { Button } from "easyest";

//相當(dāng)于
import "easyest/es/src/button/style/index.css";
import "easyest/es/src/button/index.mjs";

從而實(shí)現(xiàn)按需引入,這里不再過多展開這些插件的使用,因?yàn)楸酒恼碌闹攸c(diǎn)不在這里,感興趣的可以直接去查詢使用方式unplugin-vue-components

刪除打包文件

我們都知道,在打包之前是需要將前面打包的文件刪除的,所以需要先寫一個(gè)刪除函數(shù)。在此之前,我們先在 components 新建一個(gè) script 文件夾用于存放我們的腳本相關(guān)內(nèi)容,script 下的 build 文件夾里的內(nèi)容則是本篇文章要介紹的打包相關(guān)內(nèi)容。

在 script/utils 中新建 paths.ts 用于維護(hù)組件庫路徑,記得先安裝

pnpm add @types/node -D -w
import { resolve } from "path";

//組件庫根目錄
export const componentPath = resolve(__dirname, "../../");

//pkg根目錄
export const pkgPath = resolve(__dirname, "../../../");

刪除打包目錄函數(shù)可以放在 bulid/utils 中的 delpath.ts,注意這里因?yàn)榇虬蟮?easyest 包是我們最終要發(fā)布的包,所以我們需要將package.jsonREADME.md保留下來

import fs from "fs";
import { resolve } from "path";
import { pkgPath } from "./paths";
//保留的文件
const stayFile = ["package.json", "README.md"];

const delPath = async (path: string) => {
  let files: string[] = [];

  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);

    files.forEach(async (file) => {
      let curPath = resolve(path, file);

      if (fs.statSync(curPath).isDirectory()) {
        // recurse
        if (file != "node_modules") await delPath(curPath);
      } else {
        // delete file
        if (!stayFile.includes(file)) {
          fs.unlinkSync(curPath);
        }
      }
    });

    if (path != `${pkgPath}/easyest`) fs.rmdirSync(path);
  }
};
export default delPath;

使用 gulp

我們需要使用 ts 以及新的 es6 語法,而 gulp 是不支持的,所以我們需要安裝一些依賴使得 gulp 支持這些,其中 sucras 讓我們執(zhí)行 gulp 可以使用最新語法并且支持 ts

pnpm i gulp @types/gulp sucrase -D -w

在 build/index.ts 來執(zhí)行刪除流程

import delPath from "../utils/delpath";
import { series, parallel } from "gulp";
import { pkgPath } from "../utils/paths";
//刪除easyest

export const removeDist = () => {
  return delPath(`${pkgPath}/easyest`);
};

export default series(async () => removeDist());

在根目錄 easyest/package.json 添加腳本

  "scripts": {
    "build:easyest": "gulp -f packages/components/script/build/index.ts"
  },

根目錄下執(zhí)行pnpm run build:easyest就會(huì)發(fā)現(xiàn) easyest 下的文件被刪除了

Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

刪除完之后就可以開始打包樣式了

gulp 打包樣式

因?yàn)槲覀冇玫氖?less 寫的樣式,所以需要安裝gulp-less,同時(shí)在安裝一個(gè)自動(dòng)補(bǔ)全 css 前綴插件gulp-autoprefixer以及它們對(duì)應(yīng)的上面文件

pnpm add gulp-less @types/gulp-less gulp-autoprefixer @types/gulp-autoprefixer -D -w

然后寫一個(gè)打包樣式的函數(shù),這里使用到了 gulp 的destsrc函數(shù),不知道什么意思的樂意看上一篇文章 gulp 的介紹

//打包樣式
export const buildStyle = () => {
  return src(`${componentPath}/src/**/style/**.less`)
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(dest(`${pkgPath}/easyest/lib/src`))
    .pipe(dest(`${pkgPath}/easyest/es/src`));
};

打包組件

最后再寫一個(gè)打包組件的函數(shù),這里需要寫一個(gè)執(zhí)行命令的工具函數(shù),在 utils/run.ts

import { spawn } from "child_process";

export default async (command: string, path: string) => {
  //cmd表示命令,args代表參數(shù),如 rm -rf  rm就是命令,-rf就為參數(shù)
  const [cmd, ...args] = command.split(" ");
  return new Promise((resolve, reject) => {
    const app = spawn(cmd, args, {
      cwd: path, //執(zhí)行命令的路徑
      stdio: "inherit", //輸出共享給父進(jìn)程
      shell: true, //mac不需要開啟,windows下git base需要開啟支持
    });
    //執(zhí)行完畢關(guān)閉并resolve
    app.on("close", resolve);
  });
};

然后引入 run 函數(shù)

//打包組件
export const buildComponent = async () => {
  run("pnpm run build", componentPath);
};

因?yàn)榇虬鼧邮胶痛虬M件可以并行,所以最后build/index.ts

import delPath from "../utils/delpath";
import { series, parallel, src, dest } from "gulp";
import { pkgPath, componentPath } from "../utils/paths";
import less from "gulp-less";
import autoprefixer from "gulp-autoprefixer";
import run from "../utils/run";
//刪除dist

export const removeDist = () => {
  return delPath(`${pkgPath}/easyest`);
};

//打包樣式
export const buildStyle = () => {
  return src(`${componentPath}/src/**/style/**.less`)
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(dest(`${pkgPath}/easyest/lib/src`))
    .pipe(dest(`${pkgPath}/easyest/es/src`));
};

//打包組件
export const buildComponent = async () => {
  run("pnpm run build", componentPath);
};
export default series(
  async () => removeDist(),
  parallel(
    async () => buildStyle(),
    async () => buildComponent()
  )
);

最后 vite 打包的時(shí)候忽略 less 文件,components/vite.config.ts

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({
  build: {
    //打包文件目錄
    outDir: "es",
    //壓縮
    //minify: false,
    rollupOptions: {
      //忽略打包vue和.less文件
      external: ["vue", /\.less/],
      ...
  }

});

為了更好的看打包后的效果,我們可以再寫一個(gè)簡(jiǎn)單的 Icon 組件,目錄如下

Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

最后根目錄執(zhí)行pnpm run build,即可完成打包

Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

由于 vite 打包忽略了 less 文件打包,所以打包后的文件遇到.less 文件的引入會(huì)自動(dòng)跳過,所以引入代碼沒變

Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

但是我們已經(jīng)將 less 文件打包成 css 文件了,所以我們需要將代碼中的.less換成.css

在 components/vite.config.ts 中的 plugins 中新增

 plugins: [
    vue(),
    DefineOptions(),
    dts({
      entryRoot: "./src",
      outputDir: ["../easyest/es/src", "../easyest/lib/src"],
      //指定使用的tsconfig.json為我們整個(gè)項(xiàng)目根目錄下,如果不配置,你也可以在components下新建tsconfig.json
      tsConfigFilePath: "../../tsconfig.json",
    }),
    {
      name: "style",
      generateBundle(config, bundle) {
        //這里可以獲取打包后的文件目錄以及代碼code
        const keys = Object.keys(bundle);

        for (const key of keys) {
          const bundler: any = bundle[key as any];
          //rollup內(nèi)置方法,將所有輸出文件code中的.less換成.css,因?yàn)槲覀儺?dāng)時(shí)沒有打包less文件

          this.emitFile({
            type: "asset",
            fileName: key, //文件名名不變
            source: bundler.code.replace(/\.less/g, ".css"),
          });
        }
      },
    },
  ],

此時(shí)執(zhí)行pnpm run build:easyest,然后再看打包后文件引入

Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載

此時(shí).less已經(jīng)被替換成了.css,打包完畢,接下來要做的就是發(fā)布了!

關(guān)于“Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

文章題目:Vue3如何使用glup打包組件庫并實(shí)現(xiàn)按需加載
當(dāng)前鏈接:http://muchs.cn/article12/ghjegc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、、面包屑導(dǎo)航網(wǎng)站設(shè)計(jì)、響應(yīng)式網(wǎng)站Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營(yíng)