0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React開発で迷わない!importを自動でキレイに整える方法【Prettier + プラグイン】

0
Last updated at Posted at 2025-07-21

ReactやNext.jsで開発をしていると、
import文がごちゃごちゃしてくること、ありませんか?

  • react, next, @/components/..., ../utils/... などが混在していて読みにくい…
  • 手動で並び替えるのは面倒…

今回は、保存するだけでimportを自動整列できる環境構築方法を紹介します。


📌 使用ツール


📌 導入手順

① パッケージのインストール

npm install -D prettier @trivago/prettier-plugin-sort-imports 

② Prettier設定ファイルを作成

プロジェクトルートに prettier.config.js を作成:

my-app/
├── node_modules/
├── public/
├── src/
│   └── app/
│       └── ...
├── .vscode/
│   └── settings.json   ← VSCodeの保存設定
├── .gitignore
├── package.json        ← npmスクリプトや依存管理
├── tsconfig.json       ← TypeScriptの設定
├── tailwind.config.ts  ← Tailwindの設定
├── prettier.config.js  ← ✅ ←← ここに置く!
└── README.md
module.exports = {
  plugins: [
    "@trivago/prettier-plugin-sort-imports",
  ],
  importOrder: [
    "^react",
    "^next",
    "<THIRD_PARTY_MODULES>",
    "^@/app/(.*)",
    "^@/components/(.*)",
    "^@/utils/(.*)",
    "^[./]",
  ],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
};

③ VSCode設定にフォーマットを追加

.vscode/settings.json に以下を追記:

{
 "editor.formatOnSave": true,
 "editor.defaultFormatter": "esbenp.prettier-vscode"
}

これで保存時に自動で整形が効くようになります。


📌 並び替えの例

Before

import z from "zod";
import { useForm } from "react-hook-form";
import { createClient } from "@/utils/supabase/clients";
import React from "react";
import Button from "@/app/components/button/Button";

After

import React from "react";
import { useForm } from "react-hook-form";
import z from "zod";

import Button from "@/app/components/button/Button";
import { createClient } from "@/utils/supabase/clients";

📌 注意点

  • コメントの複製を防ぐため、コメントアウトは "use client"import文 の下に記載してください。
    (Prettierのimport並び替え時に、先頭コメントが複製される不具合を回避するため)
     

📌 おわりに

importの順序を自動で整えるだけで、コードの見通しや可読性が大幅にアップします!
まだ導入していない方はぜひ試してみてください!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?