编写ts工具库

57 阅读1分钟

创建项目

# 创建项目目录并初始化
mkdir my-utils && cd my-utils
pnpm init -y

# 安装核心依赖(仅需 2 个包!)
pnpm add -D tsup typescript

创建项目结构

my-utils/
├── src/
│   ├── index.ts          # 主入口
│   ├── math.ts           # 数学工具
│   └── string.ts         # 字符串工具
├── package.json

添加示例代码

// src/math.ts
export const add = (a: number, b: number) => a + b;
export const multiply = (a: number, b: number) => a * b;

// src/string.ts
export const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);

// src/index.ts
export * from './math';
export * from './string';

配置 package.json

{
  "name": "my-utils",
  "version": "1.0.3",
  "main": "index.js",
  "scripts": {
    "build": "tsup src/index.ts --format cjs,esm --dts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "tsup": "^8.5.0",
    "typescript": "^5.8.3"
  },
  "publishConfig": {
    "registry": "http://xxx"
  },
  "files": [
    "dist"
  ],
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.js"
    }
  }
}

打包生成dist

npm run build

image.png

发包 npm publish

安装包

image.png

  • js或ts项目都可以使用ts库
import { add } from "my-utils";
console.log("add", add(5, 8));