1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Prettier】Astro + Prettierで設定が反映されない時の原因と解決方法

Posted at

はじめに

Astroで開発をしている際、Prettierのタブ設定や折り返し(printWidth)の設定がうまく反映されなくなったため、今回その原因と解決方法を記事としてまとめました。

この記事は個人的なアウトプットを目的として作成したものです。そのため、誤った情報や不足している内容が含まれている可能性があります。もし間違いや気になる点がございましたら、ぜひご指摘いただけますと幸いです

現象

普段と同じようにフォーマットを実行したところ、設定しているはずのルールが効かず、意図しないフォーマットがされてしまいました。

npx prettier . --write

原因

AstroPrettierを使う場合、以下のように公式のprettier-plugin-astroを導入し、設定ファイルで .astroファイル向けのオプションを指定する必要があります。

{
  "plugins": ["prettier-plugin-astro"],
  "overrides": [
    {
      "files": "*.astro",
      "options": {
        "parser": "astro",
      }
    }
}

しかし、Prettierは「プロジェクト直下の設定ファイル」を最優先で読み込むため、VS Code側の設定より .prettierrcが優先されます。
そのため、.prettierrc側でprintWidthbracketSameLineを指定していないと、VS Codeの設定が無視され、結果的に意図しないフォーマットになる状態が発生していました。

解決方法

設定ファイルに必要な設定を明示的に書き加えることで解決できます。

{
  "plugins": ["prettier-plugin-astro"],
  "overrides": [
    {
      "files": "*.astro",
      "options": {
        "parser": "astro",
        "printWidth": 200,
        "bracketSameLine": false
      }
    }
  ]
}

printWidth(折り返し幅)について

Prettierの推奨値は80〜120とされています。
しかし、Tailwind CSSのユーティリティを多用する場合、1行が長くなりやすいため、私は読みやすさの観点から200に設定しています。
コードが途中で折り返されるのが個人的に好みではないため、このように調整しました。

終わりに

AstroPrettierの組み合わせでは、VS Code側の設定より.prettierrcが強く効くため、設定が反映されないときはまず設定ファイルを確認するのがおすすめです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?