peter_ts_package_template
v1.0.0
Published
A TypeScript package template
Readme
Your Library Name
一个 TypeScript 库模板,支持大型项目结构,可以直接发布到 npm。
安装
npm install your-library-name使用方法
基础使用
import {
capitalize,
HttpClient,
EventEmitter,
localStorage,
VERSION
} from 'your-library-name';
// 使用工具函数
console.log(capitalize('hello')); // 输出: Hello
// 使用 HTTP 客户端
const client = new HttpClient('https://api.example.com');
const response = await client.get('/users');
// 使用事件发射器
const emitter = new EventEmitter();
emitter.on('event', (data) => console.log(data));
emitter.emit('event', 'Hello');
// 使用存储工具
localStorage.set('key', { name: 'value' });
const data = localStorage.get('key');
// 使用常量
console.log(VERSION); // 输出: 1.0.0按需导入
// 只导入需要的模块
import { capitalize, toCamelCase } from 'your-library-name/utils';
import { HttpClient } from 'your-library-name/api';
import type { ApiResponse, BaseEntity } from 'your-library-name/types';项目结构
src/
├── index.ts # 主入口文件,导出所有公共 API
├── types/ # 类型定义目录
│ ├── index.d.ts # 全局类型声明文件(.d.ts)
│ ├── index.ts # 类型定义模块入口
│ ├── api.d.ts # API 相关类型声明
│ └── third-party.d.ts # 第三方库类型声明
├── utils/ # 工具函数目录
│ ├── index.ts # 工具函数模块入口
│ ├── string.ts # 字符串工具函数
│ ├── array.ts # 数组工具函数
│ ├── date.ts # 日期工具函数
│ └── validation.ts # 验证工具函数
├── core/ # 核心功能目录
│ ├── index.ts # 核心功能模块入口
│ ├── base.ts # 基础类
│ ├── event-emitter.ts # 事件发射器
│ └── storage.ts # 存储工具
├── api/ # API 相关目录
│ ├── index.ts # API 模块入口
│ ├── client.ts # HTTP 客户端
│ └── types.ts # API 类型定义
└── constants/ # 常量定义目录
└── index.ts # 常量定义.d.ts 文件使用说明
定义全局类型
在 src/types/index.d.ts 中定义全局类型:
declare global {
interface Window {
myCustomProperty?: string;
}
}
export interface BaseEntity {
id: string | number;
createdAt: Date;
updatedAt: Date;
}
export {};为第三方库声明类型
在 src/types/third-party.d.ts 中:
declare module 'some-untyped-library' {
export function doSomething(param: string): void;
}
export {};导入类型声明
// 方式 1:直接导入
import type { BaseEntity } from './types/index.d';
// 方式 2:通过 index.ts 导入
import type { BaseEntity } from './types';详细说明请查看 ARCHITECTURE.md
开发
安装依赖
npm install构建
npm run build测试
# 运行所有测试
npm test
# 监听模式(开发时推荐)
npm run test:watch
# 生成覆盖率报告
npm run test:coverage详细的测试指南请查看 TESTING.md
构建后会生成 dist 目录,包含:
.js文件(编译后的 JavaScript).d.ts文件(类型声明文件).map文件(Source map)
发布到 npm
- 确保你已经登录 npm:
npm login更新
package.json中的name和version构建项目:
npm run build- 发布:
npm publish在其他项目中使用
详细的使用指南请查看 USAGE.md,包括:
- 发布到 npm 的完整步骤
- 本地开发使用(npm link)
- 使用本地路径引用
- 在其他项目中的导入示例
特性
- ✅ 完整的 TypeScript 类型支持
- ✅ 模块化目录结构,适合大型项目
- ✅ 支持 .d.ts 类型声明文件
- ✅ 自动生成类型声明文件
- ✅ 路径别名支持(开发时)
- ✅ Source map 支持
- ✅ 完整的工具函数库示例
- ✅ HTTP 客户端示例
- ✅ 事件系统示例
License
MIT
