@composy/performance
v0.0.1
Published
LDesign performance analysis toolkit for build metrics, budgets, reports, runtime probes, and optimization guidance.
Maintainers
Readme
@composy/performance
@composy/performance 是一个面向 Node.js / Vite 工作流的性能分析工具包,用于统一完成以下工作:
- 扫描构建产物并提取 bundle / asset 指标
- 校验 bundle 预算与 Web Vitals 预算
- 基于规则生成优化建议与综合评分
- 输出 CLI / HTML / JSON / Markdown 报告
- 保存
history.json并分析趋势 - 通过 Vite 插件在生产构建后自动生成报告
- 采集轻量运行时指标并输出类 Lighthouse 结果
当前包已经收口为 CLI + core library 形态,不再暴露独立 Dashboard。
功能概览
1. 构建产物分析
MetricsCollector/BuildMetricsCollector扫描dist等构建目录PerformanceAnalyzer串联采集、预算、建议、评分与报告组装BuildAnalyzer/BundleAnalyzer/AssetAnalyzer输出更聚焦的分析结果OptimizationEngine基于内置规则生成建议
2. 预算与评分
BudgetChecker执行 bundle 与指标预算检查BudgetManager提供预算结果汇总能力calculatePerformanceScore()汇总评分
3. 报告链路
CliReporterHtmlReporterJsonReporterMarkdownReporterGitHubActionsReportersrc/reporting/*提供报告命名、格式归一化、摘要、归一化兼容、批量写入等 helper
4. 历史与趋势
HistoryManager维护history.jsonTrendAnalyzer对比最近记录并识别回归/改善
5. 运行时探测
RuntimeMonitor通过轻量抓取估算主文档与资源时序- 支持输出统一的
RuntimeMetrics与LighthouseResult
6. Vite 集成
performancePlugin()在vite build的生产模式阶段自动采集数据- 支持自动写报告、写历史、打印 CLI 摘要
设计思路
这个包把“性能分析”拆成了五层:
types/定义统一数据结构,PerformanceReport是主交换结构。metrics/负责采集原始指标,不处理业务建议。analyzers//optimizer/负责把原始指标转换成可消费的洞察与建议。analysis/负责把采集、预算、优化建议与评分收敛成可复用服务。reporting//reporters/负责文件命名、格式归一化、兼容旧 JSON、落盘与展示。cli//plugins/负责把上述能力接到命令行与构建工作流里。
这样做的目的是让:
- 类型边界稳定
- CLI 与插件共享同一套核心逻辑
- 报告输出可以替换而不影响分析链路
- 历史与趋势分析可以直接复用统一报告结构
安装
pnpm add @composy/performance如果你只在构建流程里使用,也可以把它安装为开发依赖:
pnpm add -D @composy/performance要求:
- Node.js >= 18
- 推荐在 ESM 项目中使用
- 若使用 Vite 插件,需安装
vite
快速开始
CLI:分析构建目录
pnpm exec ldesign-performance analyze --dir dist --output .performance --format html json markdown --historyCLI:重新渲染已有 JSON 报告
pnpm exec ldesign-performance report --input .performance --format cliCLI:轻量运行时探测
pnpm exec ldesign-performance monitor --url https://example.com --output .performance/runtime --format json html markdownCLI 命令
analyze
用于分析已有构建产物。
常用参数:
--dir <directory>:构建目录,默认dist--cwd <directory>:项目工作目录,适合从 monorepo 根目录分析子项目--config <path>:配置文件路径--output <directory>:报告输出目录,默认.performance--format <formats...>:输出格式列表,默认html json--concurrency <count>:构建产物扫描并发数,默认读取配置--history:写入history.json--history-limit <count>:历史记录上限--json:仅向 stdout 输出机器可读 JSON,适合 CI/脚本消费--open:生成 HTML 后自动打开--verbose:输出更详细日志
report
用于把已有 JSON 报告重新渲染成 CLI / HTML / JSON / Markdown。
常用参数:
--input <path>:JSON 文件或报告目录--cwd <directory>:项目工作目录--output <directory>:输出目录--format <format>:目标格式,默认cli
monitor
用于对 URL 进行轻量运行时探测。
常用参数:
--url <url>:目标地址--cwd <directory>:项目工作目录,用于解析配置和输出路径--config <path>:配置文件路径--output <directory>:输出目录--format <formats...>:输出格式列表,默认json--verbose:输出更详细日志
配置
支持以下文件名:
performance.config.tsperformance.config.jsperformance.config.mjsperformance.config.cjsperformance.config.json.performancerc*
示例:
import type { PerformanceConfig } from '@composy/performance'
const config: PerformanceConfig = {
analyze: {
formats: ['html', 'json', 'markdown'],
generateReport: true,
historyLimit: 50,
concurrency: 8,
openAnalyzer: false,
outputDir: '.performance',
writeHistory: true,
},
budgets: {
bundles: [
{ maxSize: '250kb', name: 'main', warningSize: '200kb' },
{ maxSize: '500kb', name: 'total' },
],
metrics: {
cls: 0.1,
fcp: 1800,
lcp: 2500,
},
},
optimize: {
css: true,
fonts: true,
images: true,
js: true,
},
verbose: true,
}
export default configVite 集成
import { performancePlugin } from '@composy/performance'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
performancePlugin({
enabled: true,
}),
],
})插件行为:
- 仅在
vite build且mode === production时生效 - 自动扫描构建输出目录
- 可选写入报告与
history.json - 在
verbose模式下输出完整 CLI 报告
编程式 API
一步生成构建性能报告
import { PerformanceAnalyzer } from '@composy/performance'
const result = await new PerformanceAnalyzer().analyzeBuild({
buildDir: 'dist',
collectionOptions: {
concurrency: 8,
},
cwd: process.cwd(),
})
console.log(result.report)直接采集并评分
import {
BudgetManager,
calculatePerformanceScore,
MetricsCollector,
OptimizationEngine,
} from '@composy/performance'
const collector = new MetricsCollector()
const buildMetrics = await collector.collectBuildMetrics('dist', process.cwd())
const suggestions = new OptimizationEngine().generateSuggestions(buildMetrics)
const budgetResults = new BudgetManager().check(
{
bundles: [{ maxSize: '250kb', name: 'main' }],
},
buildMetrics
)
const score = calculatePerformanceScore(buildMetrics, budgetResults, suggestions)
console.log({ buildMetrics, budgetResults, score, suggestions })写入多格式报告
import { writeReportFiles } from '@composy/performance/reporting'
writeReportFiles(report, '.performance', ['html', 'json', 'markdown'], ['html', 'json'])保存历史并分析趋势
import { HistoryManager, TrendAnalyzer } from '@composy/performance'
const history = new HistoryManager('.performance', 50)
await history.addEntry(report, {
branch: process.env.GIT_BRANCH,
commit: process.env.GIT_COMMIT,
})
const recent = await history.getHistory(2)
const trend = new TrendAnalyzer().analyzeTrends(recent)报告文件约定
当前报告链路使用两类文件名:
- 时间戳文件:
performance-report-YYYYMMDD-HHMMSS.ext - 稳定别名:
performance-report.ext
查找最新报告时会:
- 先找稳定别名
- 别名不存在时按文件名时间戳回退
这能避免历史报告在复制、恢复后 mtime 变新导致误判。
公开导出
根入口导出:
- 类型:
@composy/performance - 核心模块:
analysis / config / metrics / analyzers / budget / optimizer / reporters / history / monitor / exporters - 工具函数:
utils/* - 报告 helper:
reporting/*
推荐导入方式:
import { HistoryManager, MetricsCollector, OptimizationEngine } from '@composy/performance'如果你只需要报告 helper,也可以使用子路径:
import {
findLatestReportFile,
normalizePerformanceReportInput,
writeReportFiles,
} from '@composy/performance/reporting'打包与产物
本包使用 tools/tsup-config 对应的 @composy/pack 进行打包。
当前构建策略:
- 入口:
src/**/*.ts - 输出:
dist/ - 二次拆分:
es/:ESM +.d.tslib/:CJS(统一为.js)+lib/package.json(type=commonjs)
这样可以同时满足:
exports.*.import -> es/**exports.*.require -> lib/**types -> es/**/*.d.ts
开发与校验
pnpm run typecheck
pnpm run test
pnpm run lint:check
pnpm run build说明:
test使用包内定制 Vitest 启动脚本,兼容当前 Windows 沙箱环境lint使用@antfu/eslint-configbuild通过pack调用tools/tsup-config
示例目录
License
MIT
通过 @composy/cli 统一接入
接入类型:bin
统一命令:ldesign performance
命令别名:ldesign-analyzer
包内原生 bin:ldesign-analyzer、ldesign-performance
当前包通过独立 bin 接入,统一命令会转发到包自身 CLI。
pnpm add -D @composy/cli
ldesign performance --help
ldesign tools run performance --help