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

相关推荐
发现一只大呆瓜16 小时前
深入浅出 Tree Shaking:Rollup 是如何“摇”掉死代码的?
前端·性能优化·vite
发现一只大呆瓜19 小时前
深度起底 Vite:从打包流程到插件钩子执行时序的全链路解析
前端·vite
发现一只大呆瓜1 天前
深度解密 Rollup 插件开发:核心钩子函数全生命周期图鉴
前端·vite
发现一只大呆瓜1 天前
深度解析 Rollup 配置与 Vite 生产构建流程
前端·vite
小兵阿飞2 天前
Vite 技术介绍:实现原理、应用与优化
前端·vite
Leisureconfused2 天前
【记录】Node版本兼容性问题及解决
前端·vue.js·npm·node.js
米丘3 天前
Vite 开发服务器启动时,如何将 client 注入 HTML?
javascript·node.js·vite
米丘3 天前
vite 插件 @vitejs/plugin-vue
javascript·node.js·vite
We་ct3 天前
前端包管理工具与Monorepo全面解析
前端·javascript·npm·pnpm·yarn·monorepo·包管理
李昊哲小课3 天前
安装 npm/pnpm/yarn 换国内镜像 统一目录管理全局包+缓存
前端·缓存·npm·pnpm·yarn