基于 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 天前
😎vite自动打包压缩图片和转webp的插件
vite
小kian4 天前
vite安全漏洞deny解决方案
前端·vite
BillKu6 天前
node.js、npm相关知识
前端·npm·node.js
sma2mmm6 天前
微前端实现方案对比Qiankun VS npm组件
前端·前端框架·npm
月起星九6 天前
为什么package.json里的npm和npm -v版本不一致?
前端·npm·node.js
DevinJohw6 天前
为什么我选择[email protected]
react.js·vite
阿陈陈陈7 天前
【Node.js入门笔记12---npm包】
笔记·npm·node.js
会功夫的李白7 天前
从零创建npm依赖,只需执行一条命令
npm·依赖
页面魔术7 天前
[译]专访尤雨溪: 2025年有什么计划?
前端·vue.js·vite
还是鼠鼠8 天前
Node.js 路由 - 初识 Express 中的路由
前端·vscode·前端框架·npm·node.js·express