当前位置: 首页 > java >正文

使用 TypeScript 开发并发布一个 npm 包(完整指南)

本教程将一步步教你从零开发、打包并发布一个 TypeScript 工具库到 npm。以日期时间格式化工具为例,涵盖项目初始化、Vite 打包、类型声明输出、npm 配置、实际发布等完整流程,适合开发者直接套用。


文章目录

    • 📁 项目结构预览
    • 🧱 初始化项目
    • ✍️ 编写功能模块
    • ⚙️ 配置 TypeScript
    • 🔧 配置 Vite 打包
    • 📦 配置 package.json
    • 📖 添加 README.md(简略)
    • 使用示例
    • 🧠 发布后的版本管理建议


📁 项目结构预览

ts-date-utils/
├── dist/                     # 构建产物输出目录
│   ├── types/                # 类型声明文件输出目录
│   ├── ts-date-utils.es.js  # ES 模块
│   └── ts-date-utils.umd.js # UMD 模块
├── src/
│   └── index.ts              # 工具函数主入口
├── package.json              # 项目和发布配置
├── tsconfig.json             # TypeScript 配置
├── vite.config.ts            # Vite 打包配置
├── README.md                 # 包文档说明
└── .gitignore

🧱 初始化项目

mkdir ts-date-utils && cd ts-date-utils
npm init -y
npm install typescript vite -D
npx tsc --init
npm install @types/node -D

✍️ 编写功能模块

src/index.ts

export function formatDate(date: Date, format: string = 'YYYY-MM-DD HH:mm:ss'): string {const map: Record<string, string> = {'YYYY': date.getFullYear().toString(),'MM': (date.getMonth() + 1).toString().padStart(2, '0'),'DD': date.getDate().toString().padStart(2, '0'),'HH': date.getHours().toString().padStart(2, '0'),'mm': date.getMinutes().toString().padStart(2, '0'),'ss': date.getSeconds().toString().padStart(2, '0')};return format.replace(/YYYY|MM|DD|HH|mm|ss/g, m => map[m]);
}export function formatTimestamp(timestamp: number, format: string = 'YYYY-MM-DD HH:mm:ss'): string {return formatDate(new Date(timestamp), format);
}export function now(format: string = 'YYYY-MM-DD HH:mm:ss'): string {return formatDate(new Date(), format);
}export function parseDateString(str: string): Date {return new Date(str.replace(/-/g, '/'));
}export function isValidDate(val: unknown): val is Date {return val instanceof Date && !isNaN(val.getTime());
}

⚙️ 配置 TypeScript

tsconfig.json

{"compilerOptions": {"target": "ES2020","module": "ESNext","lib": ["ES2020", "DOM", "DOM.Iterable"],"moduleResolution": "node","esModuleInterop": true,"declaration": true,"declarationDir": "dist/types","emitDeclarationOnly": true,"outDir": "dist","skipLibCheck": true,"isolatedModules": true,"moduleDetection": "force","strict": true,"noUnusedLocals": true,"noUnusedParameters": true,"noFallthroughCasesInSwitch": true,"noUncheckedSideEffectImports": true,"types": ["node"]},"include": ["src"]
}

🔧 配置 Vite 打包

vite.config.ts

import { defineConfig } from 'vite';
import { resolve } from 'path';export default defineConfig({build: {lib: {entry: resolve(__dirname, 'src/index.ts'),name: 'TsDateUtils',fileName: (format) => `ts-date-utils.${format}.js`,formats: ['es', 'umd']},rollupOptions: {external: [],output: {globals: {}}}}
});

📦 配置 package.json

{"name": "kaze-ts-date-utils","version": "1.0.0","description": "A simple and flexible TypeScript date formatting library","main": "dist/ts-date-utils.umd.js","module": "dist/ts-date-utils.es.js","types": "dist/types/index.d.ts","files": ["dist","README.md"],"scripts": {"build": "vite build && tsc --emitDeclarationOnly","prepublishOnly": "npm run build"},"keywords": ["date","format","typescript","utils","time"],"author": "kaze","license": "MIT","devDependencies": {"@types/node": "^20.0.0","typescript": "^5.0.0","vite": "^5.0.0"}
}

📖 添加 README.md(简略)

# ts-date-utils> A simple and flexible TypeScript date formatting utility.## 安装
```bash
npm install kaze-ts-date-utils

使用示例

import { formatDate, now } from 'kaze-ts-date-utils';
console.log(now());
console.log(formatDate(new Date(), 'YYYY/MM/DD HH:mm'));

---## 🚀 发布到 npm1. 登录 npm(只需一次)
```bash
npm login
  1. 打包构建
npm run build
  1. 发布
npm publish

注意:版本号每次发布必须递增。


🧠 发布后的版本管理建议

  • bugfix / 小改动 → npm version patch
  • 新功能 → npm version minor
  • 有破坏性改动 → npm version major

发布更新:

npm version patch && npm publish

✅ 恭喜你,现在你已经掌握了完整的 TypeScript npm 包开发与发布流程!

http://www.xdnf.cn/news/3001.html

相关文章:

  • 小刚说C语言刷题——1032分糖果
  • 守护天空安全的科技利剑鼎讯信通(ACNN)的创新实践
  • Flume启动报错
  • MIT6.S081 - Lab11 networking(网络栈)
  • 阿里千问Qwen3技术解析与部署指南 :混合推理架构突破性优势与对DeepSeek R1的全面超越
  • Scrapy框架之CrawlSpider爬虫 实战 详解
  • 23种设计模式-行为型模式之解释器模式(Java版本)
  • Leetcode 3529. Count Cells in Overlapping Horizontal and Vertical Substrings
  • 关于汇编语言与程序设计——子程序设计
  • Android WIFI体系
  • Vue基础(一) 基础用法
  • 【Delphi】简化数据库读写(Helper)
  • Canvas基础篇:绘制矩形
  • 废品回收小程序:全链路数字化解决方案,赋能绿色未来
  • SDC命令详解:使用get_nets命令进行查询
  • windows如何使用cmd命令翻转屏幕
  • 多源数据整合与数据虚拟化:构建灵活、高效的数据架构
  • RPG2.设置角色摄像机
  • js day9
  • 按键精灵安卓ios辅助工具脚本:实用的文件插件(lua开源)
  • 解决ktransformers v0.3 docker镜像中 operator torchvision::nms does not exist 问题
  • Redis入门到实战——基础篇
  • JavaSE第12篇:接口interface
  • Shopify网上商店GraphQL Admin接口查询实战
  • keep-alive具体使用方法
  • 我心中的现代前端大厦
  • LabVIEW模板之温度监测应用
  • dx11 龙宝书 第五 六章 流水线
  • leetcode 2962. 统计最大元素出现至少 K 次的子数组 中等
  • 规范编码策略以及AST的应用的学习