
Commitlint
- 101 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Helps with git & pull requests tasks.
About
commitlint is a Claude Code skill for git & pull requests. It helps solo builders move faster with AI-assisted coding.
- commitlint
- Git & Pull Requests
- AI-coding skill
Commitlint by the numbers
- 101 all-time installs (skills.sh)
- Ranked #226 of 733 Git & Pull Requests skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill commitlintAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 101 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Helps with git & pull requests tasks.
Files
commitlint リファレンス
commitlint 公式ドキュメントの全 API・ガイドを網羅したスキル。 ユーザーのタスクに応じて適切な README.md を読み、そこから個別ファイルへ辿ること。
ディレクトリ構成
skills/commitlint/
SKILL.md
references/
guides/
README.md
ai-agents.md
ci-setup.md
getting-started.md
local-setup.md
use-prompt.md
reference/
README.md
cli.md
community-projects.md
configuration.md
examples.md
plugins.md
prompt.md
rules.md
rules-configuration.md
api/
README.md
format.md
lint.md
load.md
read.md
concepts/
README.md
commit-conventions.md
shareable-config.md
support/
README.md
releases.md
troubleshooting.md
upgrade.md
samples/
README.md
getting-started.md
local-setup-husky.md
custom-rules.md
shareable-config.md
ci-github-actions.md
configuration-formats.md
validate-issue-reference.md
scripts/
README.md
install.md
setup.md
cli.md
validate.md
prompt.md探索手順
タスクからカテゴリを引き、カテゴリの README.md で目的のページを特定する:
1. 下記マッピング表でタスクに対応するカテゴリを探す 2. そのカテゴリの references/{category}/README.md を参照して目的のページを特定する 3. 該当ページの .md を Read して詳細を確認する
タスク → カテゴリ マッピング
| タスク | カテゴリ | 参照 README |
|---|---|---|
| インストール、初期設定、Husky 連携、Git フック設定 | guides | references/guides/README.md |
| CI 環境(GitHub Actions 等)での commitlint 設定 | guides | references/guides/README.md |
| AI エージェント(Claude Code、Copilot、Cursor)との連携 | guides | references/guides/README.md |
| 対話型コミットメッセージ作成(prompt-cli) | guides | references/guides/README.md |
| CLI オプション、設定ファイル形式、全オプション | reference | references/reference/README.md |
| ルール一覧、ルール設定(Level / Applicable / Value) | reference | references/reference/README.md |
| プラグイン作成・登録 | reference | references/reference/README.md |
| cz-commitlint プロンプト設定 | reference | references/reference/README.md |
| @commitlint/lint, load, read, format の Node.js API | api | references/api/README.md |
| lint 結果のフォーマット・出力 | api | references/api/README.md |
| Conventional Commits フォーマット、スコープの扱い | concepts | references/concepts/README.md |
| 共有設定(shareable config)の作成・配布 | concepts | references/concepts/README.md |
| エラー解決、よくある問題のトラブルシューティング | support | references/support/README.md |
| バージョンアップグレード、validate-commit-msg 移行 | support | references/support/README.md |
| 典型的な使い方・設定例を確認したい | samples | samples/README.md |
| インストール・CLI コマンド・検証コマンドを知りたい | scripts | scripts/README.md |
@commitlint/format
lint 結果の Report を人間が読める文字列にフォーマットする。
https://commitlint.js.org/api/format
インストール
npm install --save @commitlint/format型定義
type Problem = {
level: 0 | 1 | 2;
name: string;
message: string;
};
type Report = {
results: ReportResult[];
};
type ReportResult = {
errors: Problem[];
warnings: Problem[];
};
type formatOptions = {
/** ANSI カラー出力を有効にする */
color?: boolean; // default: true
/** レベル 0, 1, 2 に対応する記号 */
signs?: readonly [string, string, string]; // default: [' ', '⚠', '✖']
/** レベル 0, 1, 2 に対応する色名 */
colors?: readonly [string, string, string]; // default: ['white', 'yellow', 'red']
/** 詳細出力を有効にする */
verbose?: boolean; // default: false
/** ヘルプ URL を付与する */
helpUrl?: string;
};関数シグネチャ
format(report?: Report = {}, options?: formatOptions = {}) => string[];インポート
import format from "@commitlint/format";使用例
空の呼び出し(問題なし)
format();
/*
[
'\u001b[1m\u001b[32m✔\u001b[39m found 0 problems, 0 warnings\u001b[22m'
]
*/カラーなしで出力
format(
{
results: [
{
warnings: [
{
level: 0,
name: "some-hint",
message: "This will not show up as it has level 0",
},
{
level: 1,
name: "some-warning",
message: "This will show up yellow as it has level 1",
},
],
errors: [
{
level: 2,
name: "some-error",
message: "This will show up red as it has level 2",
},
],
},
],
},
{
color: false,
},
);
/*
[
'✖ This will show up red as it has level 2 [some-error]',
' This will not show up as it has level 0 [some-hint]',
'⚠ This will show up yellow as it has level 1 [some-warning]',
'✖ found 1 problems, 2 warnings'
]
*/@commitlint/lint
コミットメッセージをルールに基づいて検証する。
https://commitlint.js.org/api/lint
インストール
npm install --save @commitlint/lint型定義
type RuleLevel = 0 | 1 | 2;
type RuleCondition = 'always' | 'never';
type RuleOption = any;
type PrimitiveRule = [RuleLevel, RuleCondition, RuleOption?];
type AsyncRule = Promise<PrimitiveRule>;
type FunctionRule = () => PrimitiveRule;
type AsyncFunctionRule = () => Promise<PrimitiveRule>;
type Rule = PrimitiveRule | FunctionRule | AsyncFunctionRule;
type Problem = {
level: number;
valid: boolean;
name: string;
message: string;
};
type Report = {
valid: boolean;
errors: Problem[];
warnings: Problem[];
};
type Options = {
parserOpts?: any;
};関数シグネチャ
lint(message: string, rules: {[ruleName: string]: Rule}, opts?: Options) => Promise<Report>;インポート
import lint from "@commitlint/lint";使用例
基本呼び出し
const report = await lint("foo: bar");
console.log(report);
// => { valid: true, errors: [], warnings: [] }ルール検証(valid)
const report = await lint("foo: bar", { "type-enum": [1, "always", ["foo"]] });
console.log(report);
// => { valid: true, errors: [], warnings: [] }ルール検証(invalid)
const report = await lint("foo: bar", { "type-enum": [1, "always", ["bar"]] });
console.log(report);
// => { valid: true, errors: [], warnings: [{ level: 1, valid: false, name: 'type-enum', message: '...' }] }カスタムパーサーオプション
const opts = {
parserOpts: {
headerPattern: /^(\w*)-(\w*)/,
headerCorrespondence: ["type", "scope"],
},
};
const report = await lint(
"foo-bar",
{ "type-enum": [2, "always", ["foo"]] },
opts,
);設定読み込みとの併用
import load from "@commitlint/load";
import lint from "@commitlint/lint";
const CONFIG = {
extends: ["@commitlint/config-conventional"],
};
const opts = await load(CONFIG);
const report = await lint(
"foo: bar",
opts.rules,
opts.parserPreset ? { parserOpts: opts.parserPreset.parserOpts } : {},
);Git 履歴の確認
import lint from "@commitlint/lint";
import read from "@commitlint/read";
const RULES = {
"type-enum": [2, "always", ["foo"]],
};
const commits = await read({ to: "HEAD", from: "HEAD~2" });
console.info(commits.map((commit) => lint(commit, RULES)));直近コミットのチェック
import load from "@commitlint/load";
import read from "@commitlint/read";
import lint from "@commitlint/lint";
const { rules, parserPreset } = await load();
const [commit] = await read({ from: "HEAD~1" });
const report = await lint(
commit,
rules,
parserPreset ? { parserOpts: parserPreset.parserOpts } : {},
);
console.log(JSON.stringify(report.valid));@commitlint/load
共有設定や inline ルールを解決し、最終的な Config オブジェクトを返す。
https://commitlint.js.org/api/load
インストール
npm install --save @commitlint/load型定義
type RuleLevel = 0 | 1 | 2;
type RuleCondition = 'always' | 'never';
type RuleOption = any;
type PrimitiveRule = [RuleLevel, RuleCondition, RuleOption?];
type AsyncRule = Promise<PrimitiveRule>;
type FunctionRule = () => PrimitiveRule;
type AsyncFunctionRule = () => Promise<PrimitiveRule>;
type Rule = PrimitiveRule | FunctionRule | AsyncFunctionRule;
type ParserPreset = {
name: string;
path: string;
opts: any;
};
type Seed = {
extends?: string[];
parserPreset?: string;
rules?: {[ruleName: string]: Rule};
helpUrl?: string;
};
type Config = {
extends: string[];
parserPreset?: ParserPreset;
rules: {[ruleName: string]: Rule};
helpUrl?: string;
};
type LoadOptions = {
file?: string;
cwd: string;
};関数シグネチャ
load(seed: Seed = {}, options?: LoadOptions = {cwd: process.cwd()}) => Promise<Config>;インポート
import load from "@commitlint/load";使用例
インラインルール
const config = await load({
rules: {
"body-leading-blank": [2, "always"],
},
});
console.log(config);
// => { extends: [], rules: { 'body-leading-blank': [ 2, 'always' ] } }ファイル参照(extends)
const config = await load({ extends: ["./package"] });
console.log(config);
// => { extends: ['./package', './package-b'], rules: {} }インライン parserPreset
const config = await load({ parserPreset: "./parser-preset.js" });
console.log(config);
/*
{
extends: [],
rules: {},
parserPreset: {
name: './parser-preset.js',
path: './parser-preset.js',
opts: {}
}
}
*/設定ファイルの読み込み
const config = await load(
{},
{ file: ".commitlintrc.yml", cwd: process.cwd() },
);
console.log(config);
/*
{
extends: [],
rules: {
'body-leading-blank': [ 1, 'always' ]
},
formatter: '@commitlint/format',
plugins: {}
}
*/@commitlint/read
Git リポジトリからコミットメッセージを読み取る。
https://commitlint.js.org/api/read
インストール
npm install --save @commitlint/read型定義
type Range = {
/** Lower end of the commit range to read */
from?: string;
/** Upper end of the commit range to read */
to?: string;
/** Read from ./.git/COMMIT_EDITMSG or custom path */
edit?: boolean | string;
};関数シグネチャ
read(range: Range) => Promise<string[]>;インポート
import read from "@commitlint/read";使用例
edit フラグ(COMMIT_EDITMSG から読み取り)
const result = await read({ edit: true });
console.info(result);
// => ['I did something\n\n']直近 2 コミットの読み取り
const result = await read({ from: "HEAD~2" });
console.info(result);
// => ['I did something\n\n', 'Initial commit\n\n']範囲指定
const result = await read({ from: "HEAD~2", to: "HEAD~1" });
console.info(result);
// => ['Initial commit\n\n']カスタムファイルからの読み取り
const result = await read({ edit: "./git/GITGUI_EDITMESSAGE" });
console.info(result);
// => ['I did something via git gui\n\n']api
| Name | Description | Path |
|---|---|---|
| @commitlint/format | lint 結果の Report を人間が読める文字列にフォーマットする。 | format.md |
| @commitlint/lint | コミットメッセージをルールに基づいて検証する。 | lint.md |
| @commitlint/load | 共有設定や inline ルールを解決し、最終的な Config オブジェクトを返す。 | load.md |
| @commitlint/read | Git リポジトリからコミットメッセージを読み取る。 | read.md |
Commit Conventions
コミット規約の目的・フォーマット・スコープの扱い。
参照元: https://commitlint.js.org/concepts/commit-conventions
概要
コミット規約(Commit conventions)により、チームは git 履歴にセマンティックな意味を付与できる。type、scope、breaking changes などの構造化された情報を含めることで、ツールがプロジェクトリリースに有用な情報を導出できるようになる。
コミット規約が可能にすること
- 自動化されたリッチな changelog の生成 — コミットの type や scope に基づいて変更履歴を自動生成
- 自動バージョンバンプ — breaking changes や feature の有無からセマンティックバージョニングを自動決定
- テストハーネスの実行フィルタリング — 変更された scope に基づいてテストの実行範囲を制御
基本フォーマット
Conventional Commits 仕様に基づく標準的なコミットメッセージの構造:
type(scope?): subject
body?
footer?| 要素 | 必須 | 説明 |
|---|---|---|
type | 必須 | コミットの種類(feat, fix, chore など) |
scope | 任意 | 変更の影響範囲(括弧で囲む) |
subject | 必須 | 変更の簡潔な説明 |
body | 任意 | 変更の詳細な説明 |
footer | 任意 | breaking changes や issue 参照など |
? が付いている要素は省略可能。
コミットメッセージの例
feat(lang): add Polish languagefix(middleware): ensure Range requests adhere to RFC 2616
Add one new dependency, use `range-parser` (Express dependency) to compute
range. It is tested in the determine-length case.
Fixes #2310複数スコープのサポート
commitlint は複数スコープをサポートしている。スコープのセグメントはデリミタ(区切り文字)で分割できる。
デフォルトデリミタ
デフォルトで使用可能なデリミタは以下の 3 つ:
/(スラッシュ)\(バックスラッシュ),(カンマ)
複数スコープの例
feat(ui/button): add hover animationfix(api,auth): resolve token refresh issueデリミタのカスタマイズ
使用可能なデリミタのセットは scope-delimiter-style ルールでカスタマイズできる。
export default {
rules: {
'scope-delimiter-style': [2, 'always', '/'],
},
};これにより、許可されるデリミタをプロジェクトの規約に合わせて制限・変更できる。
Concepts
| Name | Description | Path |
|---|---|---|
| Commit Conventions | コミット規約の目的・フォーマット・スコープの扱い。 | commit-conventions.md |
| Shareable Config | 共有設定の作成・配布・使用方法。 | shareable-config.md |
Shareable Config
共有設定の作成・配布・使用方法。
参照元: https://commitlint.js.org/concepts/shareable-config
概要
共有設定(Shareable config)は、commitlint のルールセットを npm パッケージとして配布・再利用するための仕組み。.rules を含むオブジェクトをデフォルトエクスポートする npm パッケージとして提供される。
共有設定の構造
共有設定パッケージは、rules プロパティを持つオブジェクトをエクスポートする:
// commitlint-config-example/index.js
export default {
rules: {
'body-leading-blank': [2, 'always'],
'header-max-length': [2, 'always', 72],
},
};extends での使用
npm パッケージ
extends 配列にパッケージ名を指定する。commitlint-config- プレフィックスは省略できる:
/**
* @type {import('@commitlint/types').UserConfig}
*/
export default {
extends: ['example'], // => commitlint-config-example
};パッケージのインストール:
npm install --save-dev commitlint-config-exampleスコープ付きパッケージ
スコープ付きパッケージはフルパスで指定する:
export default {
extends: ['@commitlint/config-conventional'],
};スコープ名のみを指定すると、<scope>/commitlint-config として解決される:
export default {
extends: ['@coolcompany'], // => @coolcompany/commitlint-config
};注意: スコープ付きパッケージが <scope>/commitlint-config の命名規則に従っていない場合は、フルパッケージ名を指定する必要がある。ローカル設定(相対パス)
ドット(.)で始まる相対パスを指定すると、ローカルファイルとして解決される:
export default {
extends: ['./example'], // => ./example.js
};マージの仕組み
extends で指定された共有設定のルールは、ローカルの commitlint.config.js に定義されたルールとマージされる。
再帰的マージ
マージは再帰的に動作する。共有設定自体がさらに別の共有設定を extends している場合、そのチェーンは無限にたどられる:
commitlint.config.js
└── extends: commitlint-config-a
└── extends: commitlint-config-b
└── extends: commitlint-config-cこの場合、commitlint-config-c → commitlint-config-b → commitlint-config-a → ローカル設定の順にマージされ、後から指定されたルールが優先される。
ローカルルールの優先
ローカル設定で定義したルールは、共有設定のルールを上書きする:
export default {
extends: ['@commitlint/config-conventional'],
rules: {
// 共有設定の header-max-length ルールを上書き
'header-max-length': [2, 'always', 100],
},
};パッケージ命名規則
| パターン | 解決先 |
|---|---|
'example' | commitlint-config-example |
'@scope/example' | @scope/commitlint-config-example |
'@scope' | @scope/commitlint-config |
'@scope/config-conventional' | @scope/config-conventional(そのまま) |
'./local' | ./local.js(ローカルファイル) |
AI Agents
Source: https://commitlint.js.org/guides/ai-agents
AI コーディングエージェント(Claude Code、Copilot、Cursor など)が commitlint のルールに従ってコミットメッセージを生成・検証するための設定方法。
Agent Skills 形式によるインストール
Agent Skills 形式をサポートするツール向けに、commitlint は専用スキルを提供している。
mkdir -p .claude/skills/committing-with-commitlint
curl -fLo .claude/skills/committing-with-commitlint/SKILL.md \
https://raw.githubusercontent.com/conventional-changelog/commitlint/master/skills/committing-with-commitlint/SKILL.mdAgent Skills 非対応ツールでの設定
AGENTS.md または CLAUDE.md に以下の指示を追加する:
- 設定確認:
npx commitlint --print-config jsonで有効なルールを取得する - メッセージ検証:
printf '%s' "<message>" | npx commitlintでコミット前に検証する - エラー発生時は括弧内のルール名を確認して修正する
git commit --no-verifyは使用禁止
エージェント向け CLI プリミティブ
| コマンド | 用途 |
|---|---|
npx commitlint --print-config json | JSON 形式で現在の設定を出力 |
| `printf '%s' "<message>" \ | npx commitlint` |
npx commitlint --last | 最後のコミットをリント |
npx commitlint --edit $1 | コミットメッセージファイルを検証(フック用) |
npx commitlint --strict | 警告でコード 2、エラーでコード 3 を返す |
LLM 向けドキュメント
commitlint の公式ドキュメントはテキスト形式でも提供されている:
https://commitlint.js.org/llms.txt— ページインデックスhttps://commitlint.js.org/llms-full.txt— 全ページの完全なマークダウン
Related
- CLI Reference
- Getting Started
- Configuration
CI Setup
CI 環境での commitlint の設定。各種 CI/CD プラットフォームでの設定例。
参照元: https://commitlint.js.org/guides/ci-setup
CI サーバー上で commitlint を実行することで、コミット規約を確実に適用できる。
GitHub Actions
name: CI
on: [push, pull_request]
permissions:
contents: read
jobs:
commitlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: lts/*
cache: npm
- name: Install commitlint
run: npm install -D @commitlint/cli @commitlint/config-conventional
- name: Print versions
run: |
git --version
node --version
npm --version
npx commitlint --version
- name: Validate current commit (last commit) with commitlint
if: github.event_name == 'push'
run: npx commitlint --last --verbose
- name: Validate PR commits with commitlint
if: github.event_name == 'pull_request'
run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verboseポイント:
fetch-depth: 0で完全な Git 履歴を取得するpushイベントでは--lastで最新コミットのみを検証するpull_requestイベントでは PR の全コミットを--from/--toで範囲指定して検証する
Travis CI
@commitlint/travis-cli パッケージを使用する。
npm install --save-dev @commitlint/travis-cli.travis.yml:
language: node_js
node_js:
- node
script:
- commitlint-travisCircleCI
version: 2.1
executors:
my-executor:
docker:
- image: cimg/node:current
working_directory: ~/project
jobs:
setup:
executor: my-executor
steps:
- checkout
- restore_cache:
key: lock-{{ checksum "package-lock.json" }}
- run:
name: Install dependencies
command: npm install
- save_cache:
key: lock-{{ checksum "package-lock.json" }}
paths:
- node_modules
- persist_to_workspace:
root: ~/project
paths:
- node_modules
lint_commit_message:
executor: my-executor
steps:
- checkout
- attach_workspace:
at: ~/project
- run:
name: Define environment variable with latest commit's message
command: |
echo 'export COMMIT_MESSAGE=$(git log -1 --pretty=format:"%s")' >> $BASH_ENV
source $BASH_ENV
- run:
name: Lint commit message
command: echo "$COMMIT_MESSAGE" | npx commitlint
workflows:
version: 2.1
commit:
jobs:
- setup
- lint_commit_message:
requires:
- setupGitLab CI
基本設定
lint:commit:
image: registry.hub.docker.com/library/node:alpine
variables:
GIT_DEPTH: 0
before_script:
- apk add --no-cache git
- npm install --save-dev @commitlint/config-conventional @commitlint/cli
script:
- npx commitlint --from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA}GitLab はデフォルトでgit cloneの深さを 20 コミットに制限する。GIT_DEPTH: 0を設定することでこの制限を解除する。
ビルド済みコンテナを使用する方法
stages: ["lint", "build", "test"]
lint:commit:
image:
name: registry.hub.docker.com/commitlint/commitlint:latest
entrypoint: [""]
stage: lint
script:
- commitlint --from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA}Jenkins X
Tekton パイプラインの設定:
apiVersion: tekton.dev/v1beta1
kind: PipelineRun
metadata:
name: pullrequest
spec:
pipelineSpec:
tasks:
- name: conventional-commits
taskSpec:
steps:
- name: lint-commit-messages
image: commitlint/commitlint
script: |
#!/usr/bin/env sh
. .jx/variables.sh
commitlint --extends '@commitlint/config-conventional' --from $PR_BASE_SHA --to $PR_HEAD_SHA
serviceAccountName: tekton-bot
timeout: 15mBitBucket Pipelines
image: node:18
pipelines:
pull-requests:
default:
- step:
name: Lint commit messages
script:
- npm install --save-dev @commitlint/config-conventional @commitlint/cli
- npx commitlint --from $BITBUCKET_COMMIT~$(git rev-list --count $BITBUCKET_BRANCH ^origin/$BITBUCKET_PR_DESTINATION_BRANCH) --to $BITBUCKET_COMMIT --verboseBitBucket はデフォルトで git clone の深さを 50 コミットに制限する。設定で変更可能。
Azure Pipelines
steps:
- checkout: self
fetchDepth: 0
- task: NodeTool@0
inputs:
versionSpec: "20.x"
checkLatest: true
- script: |
git --version
node --version
npm --version
npx commitlint --version
displayName: Print versions
- script: |
npm install conventional-changelog-conventionalcommits
npm install commitlint@latest
displayName: Install commitlint
- script: npx commitlint --last --verbose
condition: ne(variables['Build.Reason'], 'PullRequest')
displayName: Validate current commit (last commit) with commitlint
- script: |
echo "Accessing Azure DevOps API..."
response=$(curl -s -X GET -H "Cache-Control: no-cache" -H "Authorization: Bearer $(System.AccessToken)" $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullRequests/$(System.PullRequest.PullRequestId)/commits?api-version=6.0)
numberOfCommits=$(echo "$response" | jq -r '.count')
echo "$numberOfCommits commits to check"
npx commitlint --from $(System.PullRequest.SourceCommitId)~${numberOfCommits} --to $(System.PullRequest.SourceCommitId) --verbose
condition: eq(variables['Build.Reason'], 'PullRequest')
displayName: Validate PR commits with commitlintポイント:
fetchDepth: 0で完全な履歴を取得する- 通常の push では
--lastで最新コミットのみを検証する - PR では Azure DevOps API からコミット数を取得し、範囲指定で検証する
Codemagic
workflows:
commitlint:
name: Lint commit message
scripts:
- npx commitlint --from=HEAD~1Getting Started
commitlint のインストールと基本設定。
参照元: https://commitlint.js.org/guides/getting-started
インストール
@commitlint/cli と設定パッケージ @commitlint/config-conventional を devDependencies としてインストールする。
# npm
npm install -D @commitlint/cli @commitlint/config-conventional# yarn
yarn add -D @commitlint/cli @commitlint/config-conventional# pnpm
pnpm add -D @commitlint/cli @commitlint/config-conventional# bun
bun add -d @commitlint/cli @commitlint/config-conventional# deno
deno add -D npm:@commitlint/cli npm:@commitlint/config-conventional設定ファイルの作成
@commitlint/config-conventional を extends する設定ファイルを作成する。
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.jsこれにより以下の内容の commitlint.config.js が生成される:
export default { extends: ['@commitlint/config-conventional'] };@commitlint/config-conventional は Conventional Commits の規約に基づいたルールセットを提供する。
Node v24 に関する注意
Warning: Node v24 ではモジュールのロード方法が変更されており、commitlint の設定ファイルの読み込みに影響がある。
プロジェクトに package.json が存在しない場合、commitlint が設定を読み込めず以下のエラーが発生する可能性がある:
Please add rules to your commitlint.config.js解決策
1. `package.json` を追加して ES6 モジュールとして宣言する:
npm init es62. 設定ファイルの拡張子を `.mjs` に変更する:
commitlint.config.js を commitlint.config.mjs にリネームする。
Local Setup
Husky を使った Git フックによるローカルでのコミットメッセージ検証。
参照元: https://commitlint.js.org/guides/local-setup
ローカルでのリントは即座にフィードバックを得るのに適しているが、容易にバイパスできるため、本番レベルの検証には CI Setup との併用が推奨される。
フックの追加
Husky v9 を使用する方法
Husky をインストールし、commit-msg フックを設定する。
# npm
npm install --save-dev husky
npx husky init
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg# yarn
yarn add --dev husky
yarn husky init
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg# pnpm
pnpm add -D husky
pnpm exec husky init
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg# bun
bun add -d husky
bunx husky init
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msgWindows での注意事項
Windows 環境では、すべての Husky ファイルが UTF-8 エンコーディングであることを確認する。
PowerShell を使用する場合はエスケープが異なる:
echo "npx --no -- commitlint --edit `$1" > .husky/commit-msgnpm スクリプトを使った代替方法
npm pkg set scripts.commitlint="commitlint --edit"
echo "npm run commitlint \${1}" > .husky/commit-msgGit フックを直接使用する方法
Husky を使わずに Git の commit-msg フックを直接設定することも可能。詳細は Git のドキュメント を参照。フックのファイル名は commit-msg にする必要がある。
テスト
commitlint の動作確認
# npm
npx commitlint --from HEAD~1 --to HEAD --verbose# yarn
yarn commitlint --from HEAD~1 --to HEAD --verbose# pnpm
pnpm commitlint --from HEAD~1 --to HEAD --verbose# bun
bun commitlint --from HEAD~1 --to HEAD --verboseフックの動作確認
失敗するコミットの例
git commit -m "foo: this will fail"出力:
⧗ input: foo: this will fail
✖ type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]
✖ found 1 problems, 0 warnings
husky - commit-msg script failed (code 1)成功するコミットの例
git commit -m "chore: lint on commitmsg"commitlint は問題がない場合は何も出力しない。確認のための出力が必要な場合は --verbose フラグを使用する。
Guides
| Name | Description | Path |
|---|---|---|
| AI Agents | AI コーディングエージェント(Claude Code、Copilot、Cursor など)が commitlint のルールに従ってコミットメッセージを生成・検証するための設定方法。 | ai-agents.md |
| CI Setup | CI 環境での commitlint の設定。各種 CI/CD プラットフォームでの設定例。 | ci-setup.md |
| Getting Started | commitlint のインストールと基本設定。 | getting-started.md |
| Local Setup | Husky を使った Git フックによるローカルでのコミットメッセージ検証。 | local-setup.md |
| Use Prompt | @commitlint/prompt-cli を使った対話的なコミットメッセージ作成。 | use-prompt.md |
Use Prompt
@commitlint/prompt-cli を使った対話的なコミットメッセージ作成。
参照元: https://commitlint.js.org/guides/use-prompt
Warning: Prompt は現在メンテナンスされていない。一部の機能が期待通りに動作しない可能性がある。
インストール
@commitlint/prompt-cli を @commitlint/cli および設定パッケージと共にインストールする。
# npm
npm install --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli# yarn
yarn add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli# pnpm
pnpm add --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli# bun
bun add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli設定
設定ファイルを作成する:
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.jspackage.json に commit スクリプトを追加する:
{
"scripts": {
"commit": "commit"
}
}使い方
変更をステージングしてからプロンプトを実行する:
git add .
npm run commitgit add .
yarn commitgit add .
pnpm commitgit add .
bun commit対話的なプロンプトが起動し、commitlint のルールに準拠したコミットメッセージを作成できる。
代替手段: commitizen
commitizen 用の commitlint アダプタが 2 つ提供されている:
@commitlint/prompt
@commitlint/prompt-cli と同様の対話的な機能を commitizen 経由で提供する。
@commitlint/cz-commitlint
cz-conventional-changelog にインスパイアされた、より現代的なインターフェースを提供する。commitizen との組み合わせで使用する。
CLI Reference
Source: https://commitlint.js.org/reference/cli
commitlint の CLI オプション全一覧。
基本使用法
# stdin から読み取り
echo "feat: add feature" | commitlint
# 最後のコミットを検証
commitlint --last
# コミット範囲を検証
commitlint --from HEAD~3 --to HEAD
# 設定を表示
commitlint --print-configInput
| オプション | 説明 |
|---|---|
[input] | --edit, --env, --from, --to が省略された場合、stdin から読み取る |
Output / Display
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
-c, --color | boolean | true | カラー出力の切り替え |
-q, --quiet | boolean | false | コンソール出力の切り替え |
-V, --verbose | boolean | - | 問題のないレポートでも詳細出力を有効にする |
-o, --format | string | - | 結果の出力フォーマット |
--print-config | choices | "", "text", "json" | 解決済み設定を表示 |
Configuration
| オプション | 型 | 説明 |
|---|---|---|
-g, --config | string | 設定ファイルへのパス。設定が見つからない場合はリザルトコード 9 |
--default-config | boolean | 組み込みのデフォルト設定を使用する(設定ファイルなしでワンオフチェックに便利) |
-x, --extends | array | 拡張する共有設定の配列 |
-p, --parser-preset | string | conventional-commits-parser 用の設定プリセット |
--options | string | CLI オプションを含む JSON ファイルまたは CommonJS モジュールへのパス |
Commit Range / Analysis
| オプション | 型 | 説明 |
|---|---|---|
-e, --edit | string | 指定ファイルから最後のコミットメッセージを読み取る。フォールバックは ./.git/COMMIT_EDITMSG |
-E, --env | string | 環境変数の値で指定されたパスのファイル内のメッセージをチェック |
-f, --from | string | lint するコミット範囲の下限 |
-t, --to | string | lint するコミット範囲の上限 |
-l, --last | boolean | 最後のコミットのみを解析 |
--from-last-tag | boolean | 最後のタグを lint するコミット範囲の下限として使用 |
--git-log-args | string | スペース区切りの追加 git log 引数 |
Other Options
| オプション | 型 | デフォルト | 説明 |
|---|---|---|---|
-d, --cwd | string | 作業ディレクトリ | 実行ディレクトリ |
-H, --help-url | string | - | エラーメッセージ内のヘルプ URL |
-s, --strict | boolean | - | strict モードを有効にする。warning はリザルトコード 2、error はリザルトコード 3 |
-v, --version | boolean | - | バージョン情報を表示 |
-h, --help | boolean | - | ヘルプを表示 |
使用例
# 設定ファイルなしでデフォルト設定を使用(ワンオフ検証)
echo "feat: add new feature" | npx commitlint --default-config# 特定の設定ファイルを使用
commitlint --config commitlint.config.js
# 共有設定を拡張
commitlint --extends @commitlint/config-conventional
# コミットメッセージ編集時にフックから使用
commitlint --edit
# 環境変数からファイルパスを取得
commitlint --env COMMIT_MSG_FILE
# 最後のタグからのコミットを検証
commitlint --from-last-tag --to HEAD
# strict モードで実行
commitlint --strict
# JSON 形式で設定を表示
commitlint --print-config json
# 追加の git log 引数を指定
commitlint --from HEAD~5 --to HEAD --git-log-args "--first-parent"Community Projects
Source: https://commitlint.js.org/reference/community-projects
コミュニティによるプロジェクト一覧。
注意: これらのプロジェクトは commitlint とは一切関係がない。使用する前に内容を理解していることを確認すること。
プロジェクト一覧
Gitmoji Commit Workflow
- リンク: https://github.com/arvinxx/gitmoji-commit-workflow
- 説明: Gitmoji ベースのコミットワークフローツール
commitlint.io
- リンク: https://github.com/tomasen/commitlintio
- 説明: ダウンロードやインストールなしに、プロジェクトのコミットメッセージを整然と保つのを支援する
commitlint plugin function rules
- リンク: https://github.com/vidavidorra/commitlint-plugin-function-rules
- 説明: 関数をルール値として使用し、正規表現などを使ってコミットメッセージに基づくルールを作成する
commitlint-plugin-selective-scope
- リンク: https://github.com/ridvanaltun/commitlint-plugin-selective-scope
- 説明: 正規表現やプレーンテキストで type ごとに scope を制限する
commitlint-gitlab-ci
- リンク: https://gitlab.com/dmoonfire/commitlint-gitlab-ci/
- 説明: Gitlab CI の特性に対応し、ジョブを失敗させずに commitlint を使用するための小さなラッパー
committier
- リンク: https://github.com/iamyoki/committier
- 説明: コミットメッセージの修正とフォーマットを行う
Configuration
Source: https://commitlint.js.org/reference/configuration
commitlint の設定ファイル形式と全オプション。
設定ファイル形式
commitlint は cosmiconfig を使用して設定ファイルを解決する。以下の形式をサポート:
.commitlintrc(JSON / YAML).commitlintrc.json.commitlintrc.yaml.commitlintrc.yml.commitlintrc.js.commitlintrc.cjs.commitlintrc.mjs.commitlintrc.ts.commitlintrc.cts.commitlintrc.mtscommitlint.config.jscommitlint.config.cjscommitlint.config.mjscommitlint.config.tscommitlint.config.ctscommitlint.config.mts
package.json での定義
{
"commitlint": {
"extends": ["@commitlint/config-conventional"]
}
}CLI オプションで指定
commitlint --config commitlint.config.js設定オブジェクト(全オプション)
JavaScript (ESM)
const Configuration = {
extends: ["@commitlint/config-conventional"],
parserPreset: "conventional-changelog-atom",
formatter: "@commitlint/format",
rules: {
"type-enum": [2, "always", ["foo"]],
},
ignores: [(commit) => commit === ""],
defaultIgnores: true,
helpUrl:
"https://github.com/conventional-changelog/commitlint/#what-is-commitlint",
prompt: {
messages: {},
questions: {
type: {
description: "please input type:",
},
},
},
};
export default Configuration;CommonJS
module.exports = Configuration;TypeScript
import type { UserConfig } from "@commitlint/types";
import { RuleConfigSeverity } from "@commitlint/types";
const Configuration: UserConfig = {
extends: ["@commitlint/config-conventional"],
parserPreset: "conventional-changelog-atom",
formatter: "@commitlint/format",
rules: {
"type-enum": [RuleConfigSeverity.Error, "always", ["foo"]],
},
};
export default Configuration;各プロパティの詳細
extends
共有設定を解決して読み込む。参照するパッケージはインストール済みである必要がある。
export default {
extends: [
"lerna",
"@commitlint/config-conventional"
]
};複数の設定を指定した場合、後のものが前のものを上書きする。
parserPreset
コミットメッセージのパースに使用する設定プリセット。node で解決可能なパッケージ ID を指定する。
export default {
parserPreset: "conventional-changelog-atom",
};formatter
検証結果の出力フォーマットを指定する。
export default {
formatter: "@commitlint/format",
};rules
ルールの定義。extends で読み込んだルールを上書きできる。
export default {
rules: {
"type-enum": [2, "always", ["foo"]],
},
};詳細は rules-configuration.md および rules.md を参照。
ignores
commitlint がメッセージをスキップすべきかどうかを判定する関数の配列。
export default {
ignores: [(commit) => commit === ""],
};defaultIgnores
デフォルトの無視パターンを適用するかどうかを制御する boolean 値。デフォルトの無視パターンには、マージコミット、リバート、semver バージョンが含まれる。
export default {
defaultIgnores: true,
};helpUrl
失敗時に表示するカスタム URL。
export default {
helpUrl: "https://github.com/conventional-changelog/commitlint/#what-is-commitlint",
};prompt
@commitlint/cz-commitlint のコマンドラインインタラクションを設定するオブジェクト。
詳細は prompt.md を参照。
共有設定 (Shareable Configuration)
共有設定は以下のルールに従う:
- npm パッケージとして公開可能
commitlint-config-プレフィックス(例:commitlint-config-lerna)- スコープ付きパッケージ:
@scope/commitlint-config-name extendsで参照する際はプレフィックスを省略可能(例:"lerna"→commitlint-config-lerna)
Examples
Source: https://commitlint.js.org/reference/examples
commitlint の一般的な設定例集。
例 1: Issue / チケット番号の検証
コミットメッセージにチケット番号(例: PROJ-123)の参照を必須にする。
package.json での設定
{
"commitlint": {
"rules": {
"references-empty": [2, "never"]
},
"parserPreset": {
"parserOpts": {
"issuePrefixes": ["PROJ-"]
}
}
}
}parserOpts.issuePrefixes でチケット番号のプレフィックスパターンを指定する。references-empty を [2, "never"] に設定することで、references が空でないことを error レベルで強制する。
結果
# 成功
echo "feat: add login PROJ-123" | commitlint
# 失敗(チケット番号なし)
echo "feat: add login" | commitlint
# => references may not be empty例 2: VS Code での絵文字配置の調整
問題
一部のターミナルでは Unicode 絵文字の幅計算が正しく行われず、絵文字の後にスペースが欠落してテキストの配置がずれることがある。
解決策
絵文字の後にトレーリングスペースを追加する。
import { type UserConfig } from "@commitlint/types";
export default {
extends: ["@commitlint/config-conventional"],
prompt: {
questions: {
type: {
enum: {
build: { emoji: "🛠️ " },
chore: { emoji: "♻️ " },
ci: { emoji: "⚙️ " },
revert: { emoji: "🗑️ " },
},
},
},
},
} satisfies UserConfig;絵文字文字列の末尾にスペースを追加することで、プロンプトインターフェースでの配置の問題を修正する。
例 3: コミットメッセージに絵文字を含める
実際のコミットメッセージに絵文字を含め、かつ commitlint の検証をパスさせるための設定。headerWithEmoji: true を使用し、カスタムパーサープリセットで絵文字プレフィックス付きの header を検証する。
完全な設定 (commitlint.config.ts)
import type { ParserPreset, UserConfig } from "@commitlint/types";
import config from "@commitlint/config-conventional";
import createPreset from "conventional-changelog-conventionalcommits";
import { merge } from "lodash-es";
async function createEmojiParser(): Promise<ParserPreset> {
const emojiRegexPart = Object.values(config.prompt.questions.type.enum)
.map((value) => value.emoji.trim())
.join("|");
const parserOpts = {
breakingHeaderPattern: new RegExp(
`^(?:${emojiRegexPart})\\s+(\\w*)(?:\\((.*)\\))?!:\\s+(.*)$`
),
headerPattern: new RegExp(
`^(?:${emojiRegexPart})\\s+(\\w*)(?:\\((.*)\\))?!?:\\s+(.*)$`
),
};
const emojiParser = merge({}, await createPreset(), {
conventionalChangelog: { parserOpts },
parserOpts,
recommendedBumpOpts: { parserOpts },
});
return emojiParser;
}
const emojiParser = await createEmojiParser();
export default {
extends: ["@commitlint/config-conventional"],
parserPreset: emojiParser,
prompt: {
questions: {
type: {
enum: {
build: { emoji: "🛠️ " },
chore: { emoji: "♻️ " },
ci: { emoji: "⚙️ " },
revert: { emoji: "🗑️ " },
},
headerWithEmoji: true,
},
},
},
} satisfies UserConfig;仕組み
1. @commitlint/config-conventional の prompt.questions.type.enum から全絵文字を取得 2. 絵文字を正規表現パターンに変換し、カスタム headerPattern と breakingHeaderPattern を生成 3. conventional-changelog-conventionalcommits プリセットとマージしてカスタムパーサーを作成 4. headerWithEmoji: true により、@commitlint/cz-commitlint がコミットメッセージに絵文字を挿入
出力例
⚙️ ci(scope): short description
🛠 build(scope): short description
🐛 fix(scope): short description
✨ feat(scope): short descriptionPlugins
Source: https://commitlint.js.org/reference/plugins
commitlint のプラグインシステム。eslint のプラグイン実装に基づいている。
プラグイン命名規則
- 標準形式:
commitlint-plugin-<plugin-name>(例:commitlint-plugin-jquery) - スコープ付き:
@<scope>/commitlint-plugin-<plugin-name>(例:@myorg/commitlint-plugin-custom)
ルールの実装
プラグインは rules オブジェクトをエクスポートし、ルール ID とルール関数のマッピングを公開する。ルール ID には命名要件はない。
export default {
rules: {
"dollar-sign": function (parsed, when, value) {
// rule implementation ...
},
},
};ルール関数の引数
| 引数 | 説明 |
|---|---|
parsed | パースされたコミットメッセージオブジェクト |
when | always または never |
value | ルールに渡された値 |
ルール関数の戻り値
[
boolean, // true = パス、false = 失敗
string // 失敗時のメッセージ
]設定でのプラグインルール参照
プラグインルールは pluginname/rulename 形式で参照する。
例: commitlint-plugin-myplugin に dollar-sign ルールがある場合:
{
"plugins": ["commitlint-plugin-myplugin"],
"rules": {
"myplugin/dollar-sign": [2, "always"]
}
}ピア依存関係
プラグインの package.json で @commitlint/lint をピア依存関係として宣言する必要がある:
{
"peerDependencies": {
"@commitlint/lint": ">=7.6.0"
}
}公開時のキーワード
npm で公開する場合、package.json の keywords に以下を含めることが推奨される:
commitlintcommitlintplugin
ローカルプラグイン
プラグインを公開せずにプロジェクト内でローカルに定義できる。1 プロジェクトにつきローカルプラグインは 1 つのみ。
export default {
rules: {
"hello-world-rule": [2, "always"],
},
plugins: [
{
rules: {
"hello-world-rule": ({ subject }) => {
const HELLO_WORLD = "Hello World";
return [
subject.includes(HELLO_WORLD),
`Your subject should contain ${HELLO_WORLD} message`,
];
},
},
},
],
};テスト
# 失敗
echo "feat: random subject" | commitlint
# => Your subject should contain Hello World message
# 成功
echo "feat: Hello World" | commitlint
# => パスPrompt
Source: https://commitlint.js.org/reference/prompt
@commitlint/cz-commitlint のプロンプト設定。settings、messages、questions の 3 つのフィールドで構成される。
完全な設定例
export default {
parserPreset: "conventional-changelog-conventionalcommits",
rules: {
// ...
},
prompt: {
settings: {},
messages: {
skip: ":skip",
max: "upper %d chars",
min: "%d chars at least",
emptyWarning: "can not be empty",
upperLimitWarning: "over limit",
lowerLimitWarning: "below limit",
},
questions: {
type: {
description: "Select the type of change that you're committing:",
enum: {
feat: {
description: "A new feature",
title: "Features",
emoji: "✨",
},
fix: {
description: "A bug fix",
title: "Bug Fixes",
emoji: "🐛",
},
docs: {
description: "Documentation only changes",
title: "Documentation",
emoji: "📚",
},
style: {
description:
"Changes that do not affect the meaning of the code",
title: "Styles",
emoji: "💎",
},
refactor: {
description:
"A code change that neither fixes a bug nor adds a feature",
title: "Code Refactoring",
emoji: "📦",
},
perf: {
description: "A code change that improves performance",
title: "Performance Improvements",
emoji: "🚀",
},
test: {
description:
"Adding missing tests or correcting existing tests",
title: "Tests",
emoji: "🚨",
},
build: {
description: "Changes affecting build or dependencies",
title: "Builds",
emoji: "🛠",
},
ci: {
description:
"Changes to CI configuration files and scripts",
title: "Continuous Integrations",
emoji: "⚙️",
},
chore: {
description:
"Other changes that don't modify src or test files",
title: "Chores",
emoji: "♻️",
},
revert: {
description: "Reverts a previous commit",
title: "Reverts",
emoji: "🗑",
},
},
},
scope: {
description: "What is the scope of this change",
},
subject: {
description: "Write a short, imperative tense description",
},
body: {
description: "Provide a longer description of the change",
},
isBreaking: {
description: "Are there any breaking changes?",
},
breakingBody: {
description: "A BREAKING CHANGE requires a body",
},
breaking: {
description: "Describe the breaking changes",
},
isIssueAffected: {
description: "Does this change affect any open issues?",
},
issuesBody: {
description: "Closed issues require a body",
},
issues: {
description: 'Add issue references (e.g. "fix #123")',
},
},
},
};settings
| プロパティ | 型 | デフォルト | 説明 |
|---|---|---|---|
enableMultipleScopes | boolean | false | 複数 scope のラジオリスト選択を有効にする |
scopeEnumSeparator | string | - | enableMultipleScopes が true の場合の複数 scope のデリミタ |
useExclamationMark | boolean | false | breaking change 時に type/scope の後に ! を付加する |
messages
プロンプトのヒントメッセージ。ローカライズに使用可能。
| プロパティ | デフォルト値 | 説明 |
|---|---|---|
skip | ":skip" | フィールドをスキップできることを示すメッセージ |
max | "upper %d chars" | 最大文字数のメッセージ(%d が文字数に置換される) |
min | "%d chars at least" | 最小文字数のメッセージ(%d が文字数に置換される) |
emptyWarning | "can not be empty" | フィールドが空の場合の警告 |
upperLimitWarning | "over limit" | 文字数上限を超えた場合の警告 |
lowerLimitWarning | "below limit" | 文字数下限を下回った場合の警告 |
questions
各対話ステップの設定。
設定可能なステップ
| ステップ | 説明 |
|---|---|
header | header 全体 |
type | コミットタイプの選択 |
scope | 変更スコープの入力 |
subject | 短い説明の入力 |
body | 詳細な説明の入力 |
footer | footer の入力 |
isBreaking | breaking change があるかの確認 |
breaking | breaking change の説明 |
breakingBody | breaking change の body(必須) |
isIssueAffected | issue に影響があるかの確認 |
issues | issue 参照の入力 |
issuesBody | クローズする issue がある場合の body |
type の enum 設定
各 type に対して以下のプロパティを設定可能:
| プロパティ | 説明 |
|---|---|
description | type の説明文 |
title | type のタイトル |
emoji | type に対応する絵文字 |
reference
| Name | Description | Path |
|---|---|---|
| CLI Reference | commitlint の CLI オプション全一覧。 | cli.md |
| Community Projects | コミュニティによるプロジェクト一覧。 | community-projects.md |
| Configuration | commitlint の設定ファイル形式と全オプション。 | configuration.md |
| Examples | commitlint の一般的な設定例集。 | examples.md |
| Plugins | commitlint のプラグインシステム。eslint のプラグイン実装に基づいている。 | plugins.md |
| Prompt | @commitlint/cz-commitlint のプロンプト設定。3 つのフィールドで構成される。 | prompt.md |
| Rules | commitlint の全ルール一覧。各ルールは [Level, Applicable, Value] で設定。 | rules.md |
| Rules Configuration | ルール設定の形式、レベル、適用モードの詳細。 | rules-configuration.md |
Rules Configuration
Source: https://commitlint.js.org/reference/rules-configuration
ルール設定の形式、レベル、適用モードの詳細。
ルール設定の構造
ルール設定は 3 つの要素で構成される配列:
[Level, Applicable, Value]Level [0..2]
| レベル | 意味 |
|---|---|
0 | ルールを無効化 |
1 | warning(警告) |
2 | error(エラー) |
Applicable always | never
| 値 | 意味 |
|---|---|
always | ルールをそのまま適用 |
never | ルールを反転して適用 |
Value
各ルール固有のパラメータ値。
設定形式
ルール設定は以下の 3 つの形式で定義できる。
形式 1: プレーン配列
直接配列として定義する。
export default {
rules: {
"header-max-length": [0, "always", 72],
},
};形式 2: 関数(同期)
同期関数として定義し、配列を返す。
export default {
rules: {
"header-max-length": () => [0, "always", 72],
},
};形式 3: 非同期関数
非同期関数として定義し、Promise<配列> を返す。
export default {
rules: {
"header-max-length": async () => [0, "always", 72],
},
};原則
Rule configurations are either of typearrayresiding on a key with the rule's name as key on therulesobject, or of typefunctionreturning typearrayorPromise<array>.
ルール設定は、rules オブジェクト上でルール名をキーとする array 型、または array もしくは Promise<array> を返す function 型のいずれかである。
使用例
warning レベルで header の最大長を制限
export default {
rules: {
"header-max-length": [1, "always", 100],
},
};error レベルで type を必須にする
export default {
rules: {
"type-empty": [2, "never"],
},
};ルールを無効化する
export default {
rules: {
"body-leading-blank": [0],
},
};非同期で外部からルール値を取得
export default {
rules: {
"scope-enum": async () => {
const scopes = await fetchScopesFromAPI();
return [2, "always", scopes];
},
},
};Rules
Source: https://commitlint.js.org/reference/rules
commitlint の全ルール一覧。各ルールは [Level, Applicable, Value] の形式で設定する。
case に指定可能な値
以下のルールで case を指定する場合に使用できる値:
lower-case— 小文字(例:somename)upper-case— 大文字(例:SOMENAME)camel-case— キャメルケース(例:someName)kebab-case— ケバブケース(例:some-name)pascal-case— パスカルケース(例:SomeName)sentence-case— 文頭のみ大文字(例:Some name)snake-case— スネークケース(例:some_name)start-case— 各語頭を大文字(例:Some Name)
---
body ルール
body-case
- 条件: body が指定された case であること
- Applicable:
always - デフォルト値:
lower-case - 設定可能な値: 上記 case 一覧
body-empty
- 条件: body が空であること
- Applicable:
never
body-full-stop
- 条件: body が指定値で終わること
- Applicable:
never - デフォルト値:
'.'
body-leading-blank
- 条件: body が空行で始まること
- Applicable:
always
body-max-length
- 条件: body が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
body-max-line-length
- 条件: body の各行が指定値以下の文字数であること(URL を含む行は除外)
- Applicable:
always - デフォルト値:
Infinity
body-min-length
- 条件: body が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
---
header ルール
header-case
- 条件: header が指定された case であること
- Applicable:
always - デフォルト値:
lower-case - 設定可能な値: 上記 case 一覧
header-full-stop
- 条件: header が指定値で終わること
- Applicable:
never - デフォルト値:
'.'
header-max-length
- 条件: header が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
72
header-min-length
- 条件: header が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
header-trim
- 条件: header の先頭・末尾に空白がないこと
- Applicable:
always
---
type ルール
type-case
- 条件: type が指定された case であること
- Applicable:
always - デフォルト値:
lower-case - 設定可能な値: 上記 case 一覧
type-empty
- 条件: type が空であること
- Applicable:
never
type-enum
- 条件: type が指定値のいずれかであること
- Applicable:
always - デフォルト値:
["build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test"]
// 使用例: 許可する type を制限
export default {
rules: {
"type-enum": [2, "always", ["feat", "fix", "docs", "chore"]],
},
};type-max-length
- 条件: type が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
type-min-length
- 条件: type が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
---
scope ルール
scope-case
- 条件: scope が指定された case であること
- Applicable:
always - デフォルト値:
lower-case - 設定可能な値: 上記 case 一覧
拡張設定(オブジェクト形式):
// オブジェクト形式で case とデリミタを指定
{
cases: ["kebab-case"],
delimiters: ["/"]
}cases: 許可する case のリストdelimiters: マルチセグメント scope を分割するデリミタ(デフォルト:["/", "\\", ","])
scope-delimiter-style
- 条件: scope 内の全デリミタが指定値と一致すること
- Applicable:
always - デフォルト値:
["/", "\\", ","]
scope-empty
- 条件: scope が空であること
- Applicable:
never
scope-enum
- 条件: scope が指定値のいずれかであること
- Applicable:
always - デフォルト値:
[](空配列 = 全て許可)
// 使用例: 許可する scope を制限
export default {
rules: {
"scope-enum": [2, "always", ["core", "ui", "api", "docs"]],
},
};拡張設定(オブジェクト形式):
// オブジェクト形式で scope とデリミタを指定
{
scopes: ["foo", "bar"],
delimiters: ["/"]
}scopes: 許可する scope 値のリストdelimiters: scope を分割するデリミタ(デフォルト:["/", "\\", ","])
注意:scope-case,scope-enum,scope-delimiter-styleを併用する場合は、同じdelimiters設定を使用すること。そうしないと scope のパースが不整合になる可能性がある。
scope-max-length
- 条件: scope が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
scope-min-length
- 条件: scope が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
---
subject ルール
subject-case
- 条件: subject が指定された case であること
- Applicable:
always - デフォルト値:
["sentence-case", "start-case", "pascal-case", "upper-case"] - 設定可能な値: 上記 case 一覧
subject-empty
- 条件: subject が空であること
- Applicable:
never
subject-exclamation-mark
- 条件: subject の
:マーカーの前に!があること - Applicable:
never
subject-full-stop
- 条件: subject が指定値で終わること
- Applicable:
never - デフォルト値:
'.'
subject-max-length
- 条件: subject が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
subject-min-length
- 条件: subject が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
---
footer ルール
footer-empty
- 条件: footer が空であること
- Applicable:
never
footer-leading-blank
- 条件: footer が空行で始まること
- Applicable:
always
footer-max-length
- 条件: footer が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
footer-max-line-length
- 条件: footer の各行が指定値以下の文字数であること
- Applicable:
always - デフォルト値:
Infinity
footer-min-length
- 条件: footer が指定値以上の文字数であること
- Applicable:
always - デフォルト値:
0
---
その他のルール
breaking-change-exclamation-mark
- 条件: header の
:マーカーの前に!があるかどうかと、footer にBREAKING CHANGE:またはBREAKING-CHANGE:にマッチする行があるかどうかの XNOR - Applicable:
always - 動作: 両方が存在するか、両方が存在しない場合にパス。一方のみ存在する場合は失敗
references-empty
- 条件: references に少なくとも 1 つのエントリがあること
- Applicable:
never
signed-off-by
- 条件: メッセージに指定値が含まれること
- Applicable:
always - デフォルト値:
'Signed-off-by:'
trailer-exists
- 条件: メッセージに指定のトレーラーが含まれること
- Applicable:
always - デフォルト値:
'Signed-off-by:'
Support
| Name | Description | Path |
|---|---|---|
| Releases | commitlint のリリースポリシーとサポート体制。 | releases.md |
| Troubleshooting | commitlint のよくある問題と解決策。 | troubleshooting.md |
| Upgrade commitlint | validate-commit-msg からの移行、およびメジャーバージョン間のアップグレードガイド。 | upgrade.md |
Releases
commitlint のリリースポリシーとサポート体制。
参照元: https://commitlint.js.org/support/releases
リリースポリシー
- セキュリティパッチ: EOL(End of Life)前のバージョンに適用される。
- 機能追加: 現行メインバージョンにのみ適用される。
サポート体制
commitlint はスポンサー付き OSS プロジェクトではない。そのため、古いリリースに対するパッチバージョンをタイムリーにリリースすることは保証できない。
古いバージョンを使用しておりセキュリティパッチが必要な場合は、PR(Pull Request)の提供を歓迎する。
リリース一覧
すべてのリリースの一覧は GitHub の README を参照。
Troubleshooting
commitlint のよくある問題と解決策。
参照元: https://commitlint.js.org/support/troubleshooting
Range error: Found invalid rule names: [...] エラー
症状
@commitlint パッケージのいずれかを更新した後、以下のようなエラーが発生する:
Found invalid rule names: header-trim.
Supported rule names are: body-case, body-empty, ...原因
node_modules 内の @commitlint パッケージ間でバージョンミスマッチが起きている。設定が要求するルールが、インストールされている @commitlint/rules に含まれていない場合に発生する。
解決策
TIP: 古いバージョンの @commitlint/config-conventional に依存する設定を使用している場合は、それらも合わせて更新する。npm update @commitlint/config-conventionalNOTE: 詳細は GitHub PR #3871 のコメントを参照。
Upgrade commitlint
validate-commit-msg からの移行、およびメジャーバージョン間のアップグレードガイド。
参照元: https://commitlint.js.org/support/upgrade
---
validate-commit-msg からの移行
デフォルト設定の場合
npm remove validate-commit-msg --save-dev
npm install --save-dev @commitlint/cli @commitlint/config-conventionalpackage.json に commitmsg スクリプトを追加する:
{
"scripts": {
"commitmsg": "commitlint -x @commitlint/config-conventional -E GIT_PARAMS"
}
}husky をインストールする:
npm install --save-dev huskyカスタム設定の場合
npm remove validate-commit-msg --save-dev
npm install --save-dev @commitlint/cli @commitlint/config-conventionalpackage.json に commitmsg スクリプトを追加する:
{
"scripts": {
"commitmsg": "commitlint -E GIT_PARAMS"
}
}husky をインストールする:
npm install --save-dev huskycommitlint.config.js を作成する:
module.exports = {
extends: ["@commitlint/config-conventional"],
rules: {
// Place your rules here
"scope-enum": [2, "always", ["a", "b"]], // error if scope is given but not in provided list
},
};validate-commit-msg のオプション対応表
{
"types": ["a", "b"], // 'type-enum': [2, 'always', ['a', 'b']]
"scope": {
"required": true, // 'scope-empty': [2, 'never']
"allowed": ["a", "b"], // 'scope-enum': [2, 'always', ['a', 'b']]; specify [0] for allowed: ["*"]
"validate": false, // 'scope-enum': [0], 'scope-empty': [0]
"multiple": false // multiple scopes are not supported in commitlint
},
"warnOnFail": false, // no equivalent setting in commitlint
"maxSubjectLength": 100, // 'header-max-length': [2, 'always', 100]
"subjectPattern": ".+", // may be configured via `parser-preset`, contact us
"subjectPatternErrorMsg": "msg", // no equivalent setting in commitlint
"helpMessage": "", // no equivalent setting in commitlint
"autoFix": false // no equivalent setting in commitlint
}---
Version 1 to 2
npm install --save-dev conventional-changelog-lint@latestBreaking changes
- CLI: なし
- Config: ワイルドカード設定は v2.0.0 で無視されるようになった(警告が表示される)
- API: なし
---
Version 2 to 3
パッケージ名が conventional-changelog-lint から commitlint にリネームされた。
npm remove --save-dev conventional-changelog-lint
npm install --save commitlint
mv .conventional-changelog-lintrc commitlint.config.jsconventional-changelog-lint のすべての呼び出しを commitlint にリネームする。
Breaking changes
CLI:
conventional-changelog-lintコマンドはcommitlintに変更されたcommitlintコマンドは@commitlint/cli経由でインストールされるようになった.conventional-changelog-lintrcはcommitlint.config.jsに変更されたcommitlintは設定ファイルをディレクトリ構造の上方向に検索しなくなった--preset | -pフラグが削除された。angularプリセットが常に使用される
Config:
.presetキーが削除された。angularプリセットが常に使用される
API:
getConfiguration(name, settings, seed)はload(seed)に変更されたgetMessages(range)はread(range)に変更されたgetPreset(name, require)は削除されたformat(report, options)はoptionsの.colorのみを参照するようになったlint(message, options)はlint(message, rules)に変更された
---
Version 4 to 5
npm remove --save-dev @commitlint/config-angular
npm install --save @commitlint/cli @commitlint/config-conventional
echo 'module.exports = {extends: ["@commitlint/config-conventional"]};'Breaking changes
- Config:
config-angularがchoretype のサポートを廃止した。conventional-changelog との互換性が壊れるため、代わりにconfig-conventionalを使用する
---
Version 7 to 8
Breaking changes
- 成功したコミットの出力がデフォルトで省略されるようになった
--verboseフラグを使用するとポジティブな出力を得られる
---
Version 8 to 9
Breaking changes
- Possible types:
improvementtype がconfig-conventionalで拒否されるようになった
---
Version 9 to 10
Breaking changes
- Node support: Node v8 はサポートされなくなった
---
Version 10 to 11
Breaking changes
- Lerna support: Lerna v2 はサポートされなくなった
---
Version 11 to 12
Breaking changes
- resolve-extends:
extendsの解決順序が右から左(right-to-left)から左から右(left-to-right)に変更された
CI Setup with GitHub Actions
Validate commit messages on every push and pull request using the official GitHub Actions workflow.
# .github/workflows/commitlint.yml
name: CI
on: [push, pull_request]
permissions:
contents: read
jobs:
commitlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup node
uses: actions/setup-node@v4
with:
node-version: lts/*
cache: npm
- name: Install commitlint
run: npm install -D @commitlint/cli @commitlint/config-conventional
- name: Validate current commit (last commit) with commitlint
if: github.event_name == 'push'
run: npx commitlint --last --verbose
- name: Validate PR commits with commitlint
if: github.event_name == 'pull_request'
run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verboseNotes
fetch-depth: 0is required so that the full git history is available for range-based validation- On
pushevents,--lastchecks only the most recent commit; on PRs,--from/--tochecks the entire PR diff - The
--verboseflag prints a confirmation message even when all commits pass - For GitLab CI, use
--from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA}and setGIT_DEPTH: 0
Configuration Formats
commitlint supports multiple config file formats; choose based on project toolchain.
TypeScript (recommended for type safety):
// commitlint.config.ts
import { type UserConfig } from '@commitlint/types';
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'header-max-length': [2, 'always', 100],
},
} satisfies UserConfig;JavaScript ESM:
// commitlint.config.js (requires "type": "module" in package.json)
export default {
extends: ['@commitlint/config-conventional'],
};JSON:
// .commitlintrc.json
{
"extends": ["@commitlint/config-conventional"],
"rules": {
"header-max-length": [2, "always", 100]
}
}YAML:
# .commitlintrc.yml
extends:
- '@commitlint/config-conventional'
rules:
header-max-length:
- 2
- always
- 100package.json field:
{
"commitlint": {
"extends": ["@commitlint/config-conventional"]
}
}Notes
- commitlint searches for config files in the order:
.commitlintrc,.commitlintrc.{json,yaml,yml,js,cjs,mjs,ts,cts,mts},commitlint.config.{js,...}, thenpackage.json - TypeScript config requires
@commitlint/typesfor theUserConfigtype - Use
--config <path>CLI flag to specify a non-standard config location - Run
npx commitlint --print-configto verify the resolved configuration regardless of format
Custom Rules
Override or extend rules in commitlint.config.js to enforce project-specific conventions.
// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
rules: {
// Restrict allowed commit types
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'chore', 'refactor']],
// Limit header to 100 characters
'header-max-length': [2, 'always', 100],
// Require scope
'scope-empty': [2, 'never'],
// Disallow uppercase in subject
'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']],
},
};Rule tuple format: [severity, applicable, value]
| Severity | Meaning |
|---|---|
0 | disabled |
1 | warning |
2 | error (blocks commit) |
Applicable is 'always' (condition must hold) or 'never' (condition must not hold).
Notes
- Rules defined locally override any rules inherited from
extends - Setting severity to
0disables a rule that comes from a shared config - Run
npx commitlint --print-configto see the final merged ruleset - Use
--strictflag to treat warnings as errors (exit code 2 for warnings, 3 for errors)
Getting Started
Install commitlint CLI and conventional config, then create a minimal config file.
# Install
npm install -D @commitlint/cli @commitlint/config-conventional
# Create config (Linux/macOS)
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js
# Test immediately (no flags — commitlint must resolve the config file just created)
echo "feat: add new feature" | npx commitlint # exit 0: valid message
echo "bad message" | npx commitlint # non-zero exit: proves the config is loadedNotes
@commitlint/config-conventionalprovides the Conventional Commits ruleset out of the box- Do not test with
--default-config: it ignores the project config file, so the test passes even ifcommitlint.config.jsis missing or broken - Without a
package.jsondeclaring"type": "module", rename config tocommitlint.config.mjs(required for Node v24+) - A non-zero exit code means the commit message failed validation; exit 0 means it passed
- Run
npx commitlint --print-configto inspect the resolved configuration
Local Setup with Husky
Enforce commit message validation automatically via the commit-msg git hook using husky.
# Install husky
npm install --save-dev husky
npx husky init
# Register commitlint as the commit-msg hook
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msgVerify the setup by making a commit that should fail:
git commit -m "foo: this will fail"
# ✖ type must be one of [build, chore, ci, docs, feat, fix, ...]Validate the last commit manually:
npx commitlint --from HEAD~1 --to HEAD --verboseNotes
- The hook file must be named
commit-msg;pre-commitis not supported by commitlint - Since v8.0.0, commitlint only outputs messages when problems are detected; use
--verbosefor positive confirmation - Local hooks can be bypassed with
git commit --no-verify; pair with CI checks for reliable enforcement - Alternative using npm script:
npm pkg set scripts.commitlint="commitlint --edit"thenecho "npm run commitlint \${1}" > .husky/commit-msg
samples
| Name | Description | Path |
|---|---|---|
| CI Setup with GitHub Actions | Validate commit messages on every push and pull request using the official… | ci-github-actions.md |
| Configuration Formats | commitlint supports multiple config file formats; choose based on project… | configuration-formats.md |
| Custom Rules | Override or extend rules in commitlint.config.js to enforce project-specific… | custom-rules.md |
| Getting Started | Install commitlint CLI and conventional config, then create a minimal config… | getting-started.md |
| Local Setup with Husky | Enforce commit message validation automatically via the commit-msg git hook… | local-setup-husky.md |
| Shareable Config | Create a reusable commitlint configuration as an npm package and consume it… | shareable-config.md |
| Validate Issue Reference | Require every commit to reference a project ticket by enforcing… | validate-issue-reference.md |
Shareable Config
Create a reusable commitlint configuration as an npm package and consume it across projects.
Package structure (`commitlint-config-myorg/index.js`):
// commitlint-config-myorg/index.js
export default {
rules: {
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'chore', 'ci', 'refactor', 'test']],
'header-max-length': [2, 'always', 100],
'scope-case': [2, 'always', 'lower-case'],
},
};Consuming project:
// commitlint.config.js
export default {
extends: ['myorg'], // resolves to commitlint-config-myorg
};Using a local relative config (monorepo):
// packages/app/commitlint.config.js
export default {
extends: ['../../commitlint-config'], // loads ../../commitlint-config.js
};Using a scoped package:
// resolves to @myorg/commitlint-config
export default {
extends: ['@myorg'],
};Notes
- Package name must follow the pattern
commitlint-config-<name>for short-hand resolution - Multiple configs can be chained:
extends: ['@commitlint/config-conventional', 'myorg']; later entries override earlier ones - A shareable config can itself extend other configs, forming an indefinite chain
- Publish to npm or reference via local path for monorepo sharing
Validate Issue Reference
Require every commit to reference a project ticket by enforcing references-empty and a custom issue prefix.
// package.json (commitlint field)
{
"commitlint": {
"rules": {
"references-empty": [2, "never"]
},
"parserPreset": {
"parserOpts": {
"issuePrefixes": ["PROJ-"]
}
}
}
}A passing commit message:
feat(auth): add OAuth login PROJ-123A failing commit message (no reference):
feat(auth): add OAuth login
# ✖ references may not be emptyNotes
"references-empty": [2, "never"]means "it must never be the case that references are empty" (i.e., at least one reference is required)issuePrefixestells the parser which strings introduce an issue reference; adjust to match your tracker (e.g.,["#", "GH-", "JIRA-"])- This can be combined with
@commitlint/config-conventionalinextendsto keep type/scope rules alongside reference requirements - Multiple prefixes are supported:
"issuePrefixes": ["PROJ-", "HOTFIX-"]
cli
commitlint CLI コマンドの使い方。
stdin からコミットメッセージを検証
echo "feat: add feature" | npx commitlint最後のコミットを検証
npx commitlint --last --verboseコミット範囲を指定して検証
npx commitlint --from HEAD~3 --to HEAD --verbose--from に指定したコミットは範囲に含まれない(exclusive)。
最後のタグからのコミットを検証
npx commitlint --from-last-tag --to HEAD --verbose設定ファイルを指定して実行
npx commitlint --config commitlint.config.js設定ファイルが見つからない場合はリザルトコード 9 で終了する。
共有設定を拡張して実行
npx commitlint --extends @commitlint/config-conventionalGit フックから実行(commit-msg フック内での使用)
npx --no -- commitlint --edit $1環境変数からファイルパスを取得して検証
npx commitlint --env COMMIT_MSG_FILEstrict モードで実行
npx commitlint --strict --from HEAD~1 --to HEADstrict モードでは warning がリザルトコード 2、error がリザルトコード 3 で終了する。
解決済み設定を JSON 形式で表示
npx commitlint --print-config json--print-config の選択肢: "" / "text" / "json"
バージョン確認
npx commitlint --versionヘルプの表示
npx commitlint --help追加の git log 引数を指定して検証
npx commitlint --from HEAD~5 --to HEAD --git-log-args "--first-parent"install
commitlint のパッケージインストール。
@commitlint/cli と config-conventional のインストール(npm)
npm install -D @commitlint/cli @commitlint/config-conventional@commitlint/cli と config-conventional のインストール(yarn)
yarn add -D @commitlint/cli @commitlint/config-conventional@commitlint/cli と config-conventional のインストール(pnpm)
pnpm add -D @commitlint/cli @commitlint/config-conventional@commitlint/cli と config-conventional のインストール(bun)
bun add -d @commitlint/cli @commitlint/config-conventional@commitlint/cli と config-conventional のインストール(deno)
deno add -D npm:@commitlint/cli npm:@commitlint/config-conventionalHusky のインストール(npm)
npm install --save-dev huskyHusky のインストール(yarn)
yarn add --dev huskyHusky のインストール(pnpm)
pnpm add -D huskyHusky のインストール(bun)
bun add -d huskyTravis CI 用パッケージのインストール
npm install --save-dev @commitlint/travis-clivalidate-commit-msg からの移行
警告: 既存の validate-commit-msg 設定を削除する破壊的操作。移行前にバックアップを確認すること。
npm remove validate-commit-msg --save-dev
npm install --save-dev @commitlint/cli @commitlint/config-conventional
npm install --save-dev huskyprompt
対話型コミットメッセージ作成ツールのインストールと使い方。
注記: @commitlint/prompt-cli は現在メンテナンスされていない。一部の機能が期待通りに動作しない可能性がある。@commitlint/prompt-cli のインストール(npm)
npm install --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli@commitlint/prompt-cli のインストール(yarn)
yarn add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli@commitlint/prompt-cli のインストール(pnpm)
pnpm add --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli@commitlint/prompt-cli のインストール(bun)
bun add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli設定ファイルの作成
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js対話型プロンプトの実行(npm)
package.json の scripts.commit に "commit" を設定済みの場合:
git add .
npm run commit対話型プロンプトの実行(yarn)
git add .
yarn commit対話型プロンプトの実行(pnpm)
git add .
pnpm commit対話型プロンプトの実行(bun)
git add .
bun commitscripts
| Name | Description | Path |
|---|---|---|
| cli | commitlint CLI コマンドの使い方。 | cli.md |
| install | commitlint のパッケージインストール。 | install.md |
| prompt | 対話型コミットメッセージ作成ツールのインストールと使い方。 | prompt.md |
| setup | 設定ファイルと Git フックの初期設定。 | setup.md |
| validate | コミットメッセージの動作確認とテスト。 | validate.md |
setup
設定ファイルと Git フックの初期設定。
設定ファイルの作成(Linux / macOS)
echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js設定ファイルの作成(Windows)
node -e "fs.writeFileSync('commitlint.config.js', process.argv[1])" "export default { extends: ['@commitlint/config-conventional'] };"Node v24 対応: package.json を ES6 モジュールとして初期化
npm init es6Node v24 環境で package.json がない場合に設定ファイルが読み込まれないエラーを回避する。代替手段として commitlint.config.js を commitlint.config.mjs にリネームすることも有効。
Husky の初期化(npm)
npx husky initHusky の初期化(yarn)
yarn husky initHusky の初期化(pnpm)
pnpm exec husky initHusky の初期化(bun)
bunx husky initcommit-msg フックの設定(Linux / macOS)
Husky の初期化後に実行する。
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msgcommit-msg フックの設定(Windows PowerShell)
echo "npx --no -- commitlint --edit `$1" > .husky/commit-msgcommit-msg フックの設定(npm スクリプト経由)
npm pkg set scripts.commitlint="commitlint --edit"
echo "npm run commitlint \${1}" > .husky/commit-msgnpm スクリプトへの commit ショートカット追加
package.json の scripts に以下を追加する:
npm pkg set scripts.commit="commit"validate
コミットメッセージの動作確認とテスト。
commitlint の動作確認(npm)
npx commitlint --from HEAD~1 --to HEAD --verbosecommitlint の動作確認(yarn)
yarn commitlint --from HEAD~1 --to HEAD --verbosecommitlint の動作確認(pnpm)
pnpm commitlint --from HEAD~1 --to HEAD --verbosecommitlint の動作確認(bun)
bun commitlint --from HEAD~1 --to HEAD --verboseバージョン情報の確認(CI でのデバッグ用)
git --version
node --version
npm --version
npx commitlint --versionフックの動作確認: 失敗するコミットの例
git commit -m "foo: this will fail"type-enum ルール違反でコミットが拒否される。
フックの動作確認: 成功するコミットの例
git commit -m "chore: lint on commitmsg"問題がない場合は出力なしで成功する。確認のための出力が必要な場合は --verbose フラグを使用する。
CircleCI での最後のコミットを検証
echo "$COMMIT_MESSAGE" | npx commitlintCOMMIT_MESSAGE は git log -1 --pretty=format:"%s" で取得した値を使用する。
Codemagic での検証
npx commitlint --from=HEAD~1