Skip to content

构建工具

构建模块基于 tsdown 提供库构建功能,支持 TypeScript 类型声明生成和 Bundle 分析。

buildLib

构建单个库。

typescript
function buildLib(config: BuildConfig): Promise<BuildResult>

参数:

参数类型默认值说明
dirstring-包目录(必须是绝对路径)
entrystring'src/index.ts'入口文件路径
dtsbooleantrue是否生成 d.ts 文件
externalstring[]-外部依赖,不打包进产物
platform'neutral' | 'node' | 'browser''neutral'构建平台
output.dirstring'dist'输出目录
output.sourcemapbooleantrue是否生成 sourcemap

返回值:

typescript
interface BuildResult {
  success: boolean
  duration: number   // 毫秒
  error?: Error
}

示例:

typescript
import { buildLib } from '@cat-kit/maintenance'
import { resolve } from 'node:path'

const result = await buildLib({
  dir: resolve(process.cwd(), 'packages/core'),
  entry: 'src/index.ts',
  dts: true,
  external: ['vue', 'react'],
  platform: 'neutral',
  output: {
    dir: 'dist',
    sourcemap: true
  }
})

if (result.success) {
  console.log(`✓ 构建完成 ${result.duration}ms`)
} else {
  console.error('✗ 构建失败:', result.error)
}

入口文件查找

如果未指定 entry,按以下顺序查找:

  1. {dir}/src/index.ts
  2. {dir}/index.ts

平台选项

说明
'neutral'浏览器和 Node.js 通用(默认)
'node'仅 Node.js
'browser'仅浏览器

构建产物

构建后在输出目录生成:

文件说明
index.jsES 模块(压缩)
index.d.tsTypeScript 类型声明
index.js.mapSourcemap(可选)
stats.htmlBundle 分析报告

使用 Monorepo 类

推荐使用 Monorepo 类进行批量构建:

typescript
import { Monorepo } from '@cat-kit/maintenance'

const repo = new Monorepo()

await repo.group(['@cat-kit/core', '@cat-kit/fe', '@cat-kit/http']).build({
  '@cat-kit/fe': {
    external: ['@cat-kit/core']
  },
  '@cat-kit/http': {
    external: ['@cat-kit/core'],
    platform: 'neutral'
  }
})

Monorepo.group().build() 相比直接使用 buildLib 的优势:

  • 依赖感知 - 自动分析包之间的依赖关系
  • 分批构建 - 按正确顺序构建,避免依赖缺失
  • 并行执行 - 同一批次内并行构建
  • 自动 external - 自动将 peerDependenciesdevDependencies 设为 external

类型定义

typescript
interface BuildConfig {
  dir: string
  entry?: string
  dts?: boolean
  external?: string[]
  platform?: 'neutral' | 'node' | 'browser'
  output?: {
    dir?: string
    sourcemap?: boolean
  }
}

interface BuildResult {
  success: boolean
  duration: number
  error?: Error
}

相关文档

基于 MIT 许可发布