できない.dev

Prettier の設定ファイル (.prettierrc) が読み込まれない

Prettier は cosmiconfig で .prettierrc 系を検出する。
ファイル名やコメント付き JSON、monorepo の階層がずれていると無視される。prettier --find-config-path <file> で実際に解決される設定パスを確認するのが最短。

公開: 更新:

症状できない · exit 1
npx prettier --find-config-path src/index.ts
[error] Can not find configure file for "src/index.ts".
解決後できた · exit 0
npx prettier --find-config-path src/index.ts
.prettierrc.json

2026-09-03 に node:20(Node.js 20.20.2 / npm 10.8.2) で実際に打って取った出力。検証環境の詳細

要約

Prettier の設定は cosmiconfig が package.json の "prettier" キー、.prettierrc、.prettierrc.json、.prettierrc.{js,cjs,mjs}、prettier.config.{js,cjs,mjs} を順に探す。
命名や配置が外れると黙って既定値で整形され、tabWidth や singleQuote の指定が反映されない。prettier --find-config-path で実際に検出されるパスを確認するのが原因切り分けの起点になる。

実行例

設定ファイルが無い状態では --find-config-path が Can not find configure file を返し、整形結果も既定のダブルクォートのままになる。.prettierrc.json を置くと同じコマンドがそのパスを出力し、singleQuote が効いてシングルクォートへ変わる。

$ npx prettier --find-config-path src/index.ts
[error] Can not find configure file for "src/index.ts".
$ echo $?
1
$ npx prettier src/index.ts
export const greet = (name: string) => "hello " + name;
$ echo $?
0
$ npx prettier --find-config-path src/index.ts
.prettierrc.json
$ echo $?
0
$ npx prettier src/index.ts
export const greet = (name: string) => 'hello ' + name;
$ echo $?
0

— 2026-09-03 時点の出力

検証環境Node.js 20.20.2 / npm 10.8.2 / Python 3.11.2 / 2026-09-03 検証(ほか 1 件)
検証日
実行環境
node:20 Debian GNU/Linux 12 (bookworm)
バージョン
  • Node.js 20.20.2
  • npm 10.8.2
  • Python 3.11.2
  • Git 2.39.5

この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。

解決策

1. 検出パスを確認する

npx prettier --find-config-path src/index.ts

何も出ない場合は 設定が見つかっていない。
期待した .prettierrc のパスが表示されるまで原因をたぐる。

2. ファイル名と書式を公式に合わせる

{
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "all"
}

コメントを書きたければ .prettierrc.cjs にする。

module.exports = {
  tabWidth: 2,
  singleQuote: true,
};

3. ワークスペースの Prettier を指す

.vscode/settings.json:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "prettier.prettierPath": "./node_modules/prettier"
}

node_modules の Prettier を強制すれば CLI と同じバージョンで動く。

よくある原因

  1. ファイル名の誤り: prettierrc.json(先頭ドット無し)や prettier.json は対象外。
    サポート対象は Configuration File(新しいタブで開く) に列挙されている。
  2. JSON 構文エラー: .prettierrc.json でコメントや末尾カンマを書くと cosmiconfig がパースに失敗して読み込めない。
    JSON5 / JSONC ではない。
  3. monorepo の階層: Prettier は整形対象ファイルから上位に向かって探す。packages/web/src/foo.ts を整形するなら、packages/web/ か repo root に .prettierrc が必要。
  4. エディタ拡張のバージョン違い: VS Code の esbenp.prettier-vscode がバンドルする Prettier と、node_modules の Prettier の差で挙動が変わる。

この手順で直った?