基于 Vite 封装工具库实践

项目背景:公司在多个项目中频繁使用相同的工具函数。为了避免每次开发新项目时都重复复制代码,决定通过 Vite 封装一个时间函数组件库。该库将被发布到 Verdaccio 供团队其他项目使用。

项目介绍

本项目封装了一个时间函数工具库,使用 Moment.js 实现时间格式化。由于 Moment.js 体积较大,打包时排除了该库。最终,通过 Vite 封装该工具库,并打包发布到 Verdaccio 私有包管理平台,供公司内部项目使用。

框架搭建

使用 pnpm 包管理器搭建 Vite 项目,并选择库打包模式:

pnpm create vite

选择框架"Others",模板"library",生成的目录结构如下:

md 复制代码
|- dist
    |-(打包后的文件)
|- lib
    |- index.ts
    |- (其他模块)
|- public
    |- vite.svg
|- src
    |- main.ts
| types
    |- index.d.ts
    |- (其他类型声明文件)
|- index.d.ts
|- index.html
|- package.json
|- tsconfig.json
|- vite.config.ts

lib 目录用于存放项目模块,src 目录用于调试,dist 存放打包后的文件,types 存放类型声明文件。

封装函数

在 lib/format.ts 中创建时间函数:

在lib目录下新建一个 format.ts,导出两个函数,用来实现时间戳和时间字符串的相互转换:

ts 复制代码
import moment, { MomentInput } from "moment";

// 时间戳转时间字符串
export function formatTimestampToDate(timestamp: MomentInput, formatter = "YYYY-MM-DD HH:mm:ss") {
  return moment(timestamp).format(formatter);
}

// 时间字符串转时间戳
export function formatDateToTimestamp(date: MomentInput) {
  return moment(date).valueOf();
}

在 lib/index.ts 中统一导出:

ts 复制代码
export { formatTimestampToDate, formatDateToTimestamp } from "./format";

注意:可使用 JSDoc 插件添加块级注释,VSCode会自动提供调用提示。安装jsdoc插件后,在函数前添加/**即可生成注释。

生成类型声明文件

删除根目录的index.d.ts文件,修改tsconfig.json,设置类型声明文件输出目录:

json 复制代码
{
  "compilerOptions": {
    "declaration": true,
    "outDir": "types",
    "emitDeclarationOnly": true
  },
  "include": ["lib"]
}

修改 package.json 的 types 属性,指向生成的类型声明文件:

json 复制代码
{
  - "types": "./index.d.ts",
  + "types": "./types/index.d.ts",
}

依赖管理

使用 peerDependencies 避免将moment打包进项目。如果项目中已经安装了moment,则不会重复打包:

json 复制代码
{
  "peerDependencies": {
    "moment": "^2.29.1"
  }
}

安装Momentjs并添加为对等依赖:

shell 复制代码
pnpm add moment --save-peer

在 vite.config.ts 中排除moment:

ts 复制代码
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    rollupOptions: {
      external: ["moment"],
      output: {
        globals: {
          moment: "moment",
        },
      },
    },
  },
});

发包

在项目根目录新建一个 .npmignore 文件,排除不需要的文件和目录:

md 复制代码
node_modules
src
lib
vite.config.ts
tsconfig.json
index.html

在 package.json 文件中配置发布文件:

json 复制代码
{
 "files": ["dist", "types"]
}

发布包到Verdaccio:

shell 复制代码
npm pubsh

注意:可以通过npm pack先生成一个包进行预览,再通过tar -tf XXX.tgz预览包。

相关推荐
libraG11 小时前
Jenkins打包问题
前端·npm·jenkins
人工智能训练师2 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny072 天前
pnpm相对于npm,yarn的优势
前端·npm·node.js
萌萌哒草头将军2 天前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite
huangql5202 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
xiaoyan20152 天前
Electron38-Winchat聊天系统|vite7+electron38+vue3电脑端聊天Exe
vue.js·electron·vite
月下点灯3 天前
✨项目上线后产品要求把应用字体改大点📏怎么办?一招教你快速解决🔧
前端·vite
李重楼3 天前
Vite 默认端口启动被拒绝解决办法
vite
xiaohe06013 天前
👋 一起写一个基于虚拟模块的密钥管理 Rollup 插件吧(三)
vite·rollup.js
风若飞3 天前
npm ERR! code CERT_HAS_EXPIRED
前端·npm·node.js