基于 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预览包。

相关推荐
越努力越幸运5087 小时前
npm常见问题解决
前端·npm·node.js
jenchoi41314 小时前
【2025-11-19】软件供应链安全日报:最新漏洞预警与投毒预警情报汇总
网络·安全·web安全·网络安全·npm
特级业务专家1 天前
续集:Vite 字体插件重构之路 —— 从“能用”到“生产级稳定”
javascript·vue.js·vite
mixboot3 天前
配置 Node.js npm镜像源 安装 Claude Code
npm·node.js·nvm·claude code
zhooson3 天前
window安装node后发现npm脚本被禁止
前端·npm·node.js
zzlyx993 天前
IoTSharp前端VUE采用npm run build编译提示require() of ES Module 出错
前端·vue.js·npm
特级业务专家3 天前
把 16MB 中文字体压到 400KB:我写了一个 Vite 字体子集插件
javascript·vue.js·vite
y***03174 天前
Node.js npm 安装过程中 EBUSY 错误的分析与解决方案
前端·npm·node.js
半开半落5 天前
uniapp通过npm使用第三方库兼容微信小程序
微信小程序·npm·uni-app
jenchoi4135 天前
【2025-11-15】软件供应链安全日报:最新漏洞预警与投毒预警情报汇总
前端·网络·安全·网络安全·npm·node.js