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

相关推荐
伊玛目的门徒2 小时前
用 npm 安装 Claude Code CLI 并对接 DeepSeek API 经验分享
人工智能·npm·大模型·ai编程·deepseek·claude code
赴前尘5 小时前
npm设置国内镜像源
npm
是谁眉眼1 天前
npm执行错误 但黑窗口node可以成功启动问题分析
前端·npm·node.js
天若有情6734 天前
自己开发一款极简 Vanilla 原生前端框架,已开源上架 NPM & GitHub
前端框架·npm·github
TT_Close4 天前
看懂 VSCode 发布中心后,下一步该把 App 发版交给 CLI 了
npm·开源·app
吴声子夜歌5 天前
Vue3——脚手架Vite
前端·javascript·vue.js·vite
DevilSeagull6 天前
电脑上安装的服务会自动消失? 推荐项目: localhostSCmanager. 更好管理你的服务!
测试工具·安全·react·vite·localhost·hono·trpc
前端之虎陈随易6 天前
有生之年系列,Nodejs进程管理pm2 v7.0发布
前端·typescript·npm·node.js
kyriewen8 天前
Webpack vs Vite:一个是“老黄牛”,一个是“猎豹”,你选谁?
前端·webpack·vite
网络点点滴8 天前
NPM的包版本管理
前端·npm·node.js