ts-library / TypeScriptライブラリ開発スキル は何をしますか?
TypeScriptライブラリやnpmパッケージを作成する際に使用します。プロジェクト設定、package.jsonのエクスポート設定、ビルドツール(tsdown/unbuild)、API設計パターン、型推論のテクニック、テスト、npm公開までを網羅します。バンドル、CJS/ESMのデュアル出力の設定、リリースワークフローの構築時に使用してください。
はじめに
このスキルは、TypeScriptライブラリの開発を効率化するためのものです。以下の主要なトピックをカバーします:
- プロジェクトの初期化と設定
package.jsonのエクスポート設定- ビルドツール(tsdown/unbuild)の設定
- API設計パターン
- 型推論のテクニック
- テスト戦略
- npmへの公開
- リリースワークフロー
プロジェクト設定
1. プロジェクトの初期化
npm init -y
2. TypeScriptの設定
tsconfig.json の例:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"skipLibCheck": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
package.jsonのエクスポート設定
CJS/ESMのデュアル出力をサポートするための package.json の例:
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
},
"files": ["dist"]
}
ビルドツール(tsdown/unbuild)
tsdown を使用する場合
tsdown.config.ts の例:
import { defineConfig } from "tsdown";
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm", "cjs"],
dts: true,
clean: true,
});
unbuild を使用する場合
build.config.ts の例:
import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
entries: ["./src/index"],
declaration: true,
clean: true,
rollup: {
emitCJS: true,
},
});
API設計パターン
関数ベースのAPI
export function createUser(name: string, age: number): User {
return { name, age };
}
オプションオブジェクトパターン
export interface Config {
baseURL: string;
timeout?: number;
headers?: Record<string, string>;
}
export function createClient(options: Config): Client {
// 実装
}
型推論のテクニック
ジェネリック制約
export function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
条件付き型
export type IsString<T> = T extends string ? true : false;
テスト
テストフレームワーク(vitest)の設定
npm install -D vitest
vitest.config.ts の例:
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "node",
},
});
テストの例:
import { describe, it, expect } from "vitest";
import { add } from "./math";
describe("add", () => {
it("should add two numbers", () => {
expect(add(1, 2)).toBe(3);
});
});
npmへの公開
公開前の確認
npm run build
npm test
公開コマンド
npm publish
リリースワークフロー
semantic-release を使用する場合
package.json への追加設定:
{
"release": {
"branches": ["main"]
},
"publishConfig": {
"access": "public"
}
}
CI設定(GitHub Actions)の例:
name: Release
on:
push:
branches: [main]
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
- run: npx semantic-release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
まとめ
このスキルを使うことで、TypeScriptライブラリの開発から公開までの全プロセスを効率的に進めることができます。プロジェクトの設定、ビルド、テスト、リリースワークフローを一貫して管理しましょう。