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

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


文章目录

    • [📁 项目结构预览](#📁 项目结构预览)
    • [🧱 初始化项目](#🧱 初始化项目)
    • [✍️ 编写功能模块](#✍️ 编写功能模块)
    • [⚙️ 配置 TypeScript](#⚙️ 配置 TypeScript)
    • [🔧 配置 Vite 打包](#🔧 配置 Vite 打包)
    • [📦 配置 package.json](#📦 配置 package.json)
    • [📖 添加 README.md(简略)](#📖 添加 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

🧱 初始化项目

bash 复制代码
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

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

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

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

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(简略)

markdown 复制代码
# ts-date-utils

> A simple and flexible TypeScript date formatting utility.

## 安装
```bash
npm install kaze-ts-date-utils

使用示例

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

## 🚀 发布到 npm

1. 登录 npm(只需一次)
```bash
npm login
  1. 打包构建
bash 复制代码
npm run build
  1. 发布
bash 复制代码
npm publish

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


🧠 发布后的版本管理建议

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

发布更新:

bash 复制代码
npm version patch && npm publish

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

相关推荐
G018_star sky♬20 分钟前
原生JavaScript实现输入验证的界面
javascript·css·css3
火龙谷24 分钟前
DrissionPage遇到iframe
开发语言·前端·javascript
千里马-horse37 分钟前
搭建 React Native 库
javascript·react native·react.js·native library
艾小码41 分钟前
从零到一:这篇JavaScript指南让你成为独立开发者
前端·javascript
月下点灯1 小时前
🏮一眼就会🗂️大文件分片上传,白送前后端全套功法
javascript·typescript·node.js
顾安r6 小时前
11.8 脚本网页 星际逃生
c语言·前端·javascript·flask
im_AMBER7 小时前
React 17
前端·javascript·笔记·学习·react.js·前端框架
一雨方知深秋7 小时前
2.fs模块对计算机硬盘进行读写操作(Promise进行封装)
javascript·node.js·promise·v8·cpython
顺凡9 小时前
删一个却少俩:Antd Tag 多节点同时消失的原因
前端·javascript·面试
前端大卫9 小时前
动态监听DOM元素高度变化
前端·javascript