VS Codeでコードのインデントを自動整形する方法|きれいにそろえて読みやすく!

プログラミング・IT

「VS Codeでコードを書いていて、インデントがぐちゃぐちゃになって見づらい」
「人によってスペースやタブの幅がバラバラ…」
こんな悩みはありませんか?

VS Codeなら、ショートカットや設定で簡単にインデントを自動整形 できます。

この記事では、VS Codeでインデントをきれいに整える方法や、保存時に自動で整形する設定、言語別の細かな調整まで、わかりやすく紹介します。

スポンサーリンク

ショートカットで一発整形

コード全体のインデントを整える

基本的な整形ショートカット

Shift + Alt + F (Windows/Linux)
Shift + Option + F (Mac)

これだけで現在開いているファイルのコードを、VS Codeのルールに従ってきれいに整形してくれます。

選択した部分のみ整形

コードの一部分だけを整形したい場合:

  1. 整形したい部分を選択
  2. Shift + Alt + Fを押す

選択された範囲のみが整形されます。

コマンドパレットからの実行

Ctrl + Shift + P (Windows/Linux)
Command + Shift + P (Mac)

コマンドパレットで「Format Document」と入力して実行することも可能です。

整形前後の例

整形前のコード

function calculateTotal(items) {
if(items.length>0){
let total=0;
for(let i=0;i<items.length;i++){
total+=items[i].price;
}
return total;
}
return 0;
}

整形後のコード

function calculateTotal(items) {
    if (items.length > 0) {
        let total = 0;
        for (let i = 0; i < items.length; i++) {
            total += items[i].price;
        }
        return total;
    }
    return 0;
}

保存時に自動で整形する設定

基本的な自動整形設定

いちいちショートカットを押すのが面倒な場合は、保存するたびに自動でインデントを整える設定にできます。

settings.jsonでの設定

settings.jsonCtrl + ,で設定を開き、右上の「{}」アイコンをクリック)に以下を追加します:

{
    "editor.formatOnSave": true
}

これで Ctrl + S(または Cmd + S)でファイルを保存するだけで、自動的に整形されます。

UI設定での変更方法

  1. Ctrl + ,で設定を開く
  2. 検索欄で「format on save」と入力
  3. 「Editor: Format On Save」にチェックを入れる

より詳細な自動整形設定

貼り付け時の自動整形

{
    "editor.formatOnPaste": true
}

コードを貼り付けたときも自動で整形されます。

入力中の自動整形

{
    "editor.formatOnType": true
}

セミコロンや括弧を入力したときに、その行が自動で整形されます。

おすすめの組み合わせ設定

{
    "editor.formatOnSave": true,
    "editor.formatOnPaste": true,
    "editor.formatOnType": true,
    "editor.codeActionsOnSave": {
        "source.fixAll": true,
        "source.organizeImports": true
    }
}

インデント幅(タブサイズ)の設定

基本的なインデント設定

全体のインデント幅を変更

{
    "editor.tabSize": 2
}

スペースかタブかの選択

{
    // スペースを使用(推奨)
    "editor.insertSpaces": true,
    "editor.tabSize": 2
}
{
    // タブ文字を使用
    "editor.insertSpaces": false,
    "editor.tabSize": 4
}

インデントの可視化

{
    "editor.renderWhitespace": "all",
    "editor.renderControlCharacters": true,
    "editor.guides.indentation": true
}

これで、スペースやタブ、インデントガイドラインが表示されて確認しやすくなります。

言語別のインデント設定

言語ごとに異なるインデント幅

{
    "[javascript]": {
        "editor.tabSize": 2,
        "editor.insertSpaces": true
    },
    "[python]": {
        "editor.tabSize": 4,
        "editor.insertSpaces": true
    },
    "[html]": {
        "editor.tabSize": 2,
        "editor.insertSpaces": true
    },
    "[css]": {
        "editor.tabSize": 2,
        "editor.insertSpaces": true
    },
    "[json]": {
        "editor.tabSize": 2,
        "editor.insertSpaces": true
    },
    "[yaml]": {
        "editor.tabSize": 2,
        "editor.insertSpaces": true
    },
    "[markdown]": {
        "editor.tabSize": 4,
        "editor.insertSpaces": true
    }
}

一般的な言語別推奨設定

言語インデント幅スペース/タブ理由
JavaScript/TypeScript2スペーススペース業界標準、Prettierデフォルト
Python4スペーススペースPEP 8準拠
HTML/CSS2スペーススペース軽量、読みやすさ
Java/C#4スペーススペース企業標準
Goタブタブ言語公式推奨
Makefileタブタブ仕様上必須

フォーマッター(整形ツール)の設定

VS Code内蔵フォーマッター

VS Codeには各言語用の内蔵フォーマッターがあります:

  • JavaScript/TypeScript: TypeScript Language Server
  • JSON: JSON Language Server
  • HTML: HTML Language Server
  • CSS: CSS Language Server

外部フォーマッターの利用

Prettier(JavaScript/TypeScript/HTML/CSS)

最も人気のあるWebフロントエンド向けフォーマッター:

  1. Prettier拡張をインストール
    • 拡張機能で「Prettier – Code formatter」を検索してインストール
  2. 設定を追加 { "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.formatOnSave": true, "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } }
  3. Prettierの設定ファイル(.prettierrc) プロジェクトルートに作成: { "semi": true, "trailingComma": "es5", "singleQuote": true, "printWidth": 80, "tabWidth": 2, "useTabs": false }

他の言語のフォーマッター

Python(Black)
{
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true
    }
}
Go(Go fmt)
{
    "[go]": {
        "editor.defaultFormatter": "golang.go",
        "editor.formatOnSave": true
    }
}
C/C++(clang-format)
{
    "[c]": {
        "editor.defaultFormatter": "ms-vscode.cpptools"
    },
    "[cpp]": {
        "editor.defaultFormatter": "ms-vscode.cpptools"
    }
}

インデント変換と統一

スペースとタブの一括変換

タブからスペースに変換

  1. コマンドパレットを開くCtrl + Shift + P
  2. 「Convert Indentation to Spaces」と入力
  3. 実行

スペースからタブに変換

  1. コマンドパレットを開くCtrl + Shift + P
  2. 「Convert Indentation to Tabs」と入力
  3. 実行

複数ファイルの一括変換

VS Code拡張「Indenticator」や「Beautify」を使用することで、プロジェクト全体のインデントを統一できます。

EditorConfigによる統一

.editorconfigファイルの作成

プロジェクトルートに.editorconfigを作成:

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# 全ファイル共通設定
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

# JavaScript/TypeScript
[*.{js,ts,jsx,tsx}]
indent_style = space
indent_size = 2

# Python
[*.py]
indent_style = space
indent_size = 4

# HTML/CSS
[*.{html,css,scss}]
indent_style = space
indent_size = 2

# JSON
[*.json]
indent_style = space
indent_size = 2

# YAML
[*.{yml,yaml}]
indent_style = space
indent_size = 2

# Makefile
[Makefile]
indent_style = tab

高度な整形設定

保存時のコードアクション

import文の自動整理

{
    "editor.codeActionsOnSave": {
        "source.organizeImports": true,
        "source.fixAll": true,
        "source.fixAll.eslint": true
    }
}

段階的な保存時アクション

{
    "editor.codeActionsOnSave": [
        "source.organizeImports",
        "source.fixAll.eslint",
        "source.addMissingImports"
    ]
}

条件付き整形

ファイルサイズによる制限

{
    "editor.formatOnSave": true,
    "editor.formatOnSaveTimeout": 750,
    "files.maxMemoryForLargeFilesMB": 4096
}

特定フォルダの除外

{
    "files.exclude": {
        "**/node_modules/**": true,
        "**/dist/**": true
    },
    "search.exclude": {
        "**/node_modules/**": true,
        "**/dist/**": true
    }
}

トラブルシューティング

よくある問題と対処法

整形が効かない場合

確認ポイント1: フォーマッターの確認
  1. コマンドパレットで「Format Document With...」を実行
  2. 利用可能なフォーマッターを確認
  3. 適切なフォーマッターを選択
確認ポイント2: 言語モードの確認

画面右下の言語モード表示をクリックして、正しい言語が設定されているか確認。

確認ポイント3: 拡張機能の競合

複数のフォーマッターがインストールされている場合、どれを使うかを明示的に指定:

{
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }
}

インデントが混在している場合

統一方法
  1. **Ctrl + Shift + P**でコマンドパレットを開く
  2. **「Reindent Lines」**を実行
  3. 全体のインデントを統一
予防設定
{
    "editor.detectIndentation": false,
    "editor.insertSpaces": true,
    "editor.tabSize": 2
}

パフォーマンス最適化

大きなファイルでの制限

{
    "editor.formatOnSave": true,
    "editor.formatOnSaveTimeout": 1500,
    "diffEditor.maxFileSize": 50
}

除外パターンの設定

{
    "files.exclude": {
        "**/.git": true,
        "**/node_modules": true,
        "**/tmp": true,
        "**/*.min.js": true,
        "**/*.min.css": true
    }
}

チーム開発での統一

プロジェクト設定の共有

.vscode/settings.jsonの作成

プロジェクト固有の設定:

{
    "editor.formatOnSave": true,
    "editor.tabSize": 2,
    "editor.insertSpaces": true,
    "[python]": {
        "editor.tabSize": 4
    },
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}

推奨拡張機能の指定

.vscode/extensions.jsonを作成:

{
    "recommendations": [
        "esbenp.prettier-vscode",
        "ms-python.black-formatter",
        "bradlc.vscode-tailwindcss",
        "EditorConfig.EditorConfig"
    ]
}

Linter(コード検査ツール)との連携

ESLint + Prettier

{
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.validate": [
        "javascript",
        "typescript",
        "javascriptreact",
        "typescriptreact"
    ],
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    }
}

package.jsonでのスクリプト設定

{
    "scripts": {
        "format": "prettier --write .",
        "format:check": "prettier --check .",
        "lint": "eslint . --ext .js,.ts,.jsx,.tsx",
        "lint:fix": "eslint . --ext .js,.ts,.jsx,.tsx --fix"
    }
}

よくある質問

Q: タブとスペース、どちらを使うべきですか?

A: 一般的にはスペースが推奨されます。理由:

  • 環境に依存しない: どのエディタでも同じ見た目
  • Webサイトやツールでの表示が安定
  • 多くのスタイルガイドで推奨

ただし、一部の言語(Go、Makefileなど)ではタブが必須または推奨の場合があります。

Q: 既存プロジェクトのインデントを統一するには?

A: 段階的なアプローチを推奨:

  1. EditorConfigを導入してルールを明確化
  2. ファイル種別ごとに少しずつ変換
  3. チーム内で合意を取ってから実行
  4. Git履歴への影響を考慮

Q: フォーマットが他の人と違ってしまいます

A: 設定の統一方法:

  1. プロジェクトに.vscode/settings.jsonを作成
  2. EditorConfigを使用
  3. Prettierなどの設定ファイルを共有
  4. チーム内でスタイルガイドを決定

Q: 特定のファイルだけフォーマットを無効にしたい

A: 複数の方法があります:

// prettier-ignore
const uglyCode = {
    a   : 1,
    b      : 2
};

または設定で除外:

{
    "files.exclude": {
        "legacy/**": true
    }
}

Q: 保存時フォーマットが遅い場合の対処法は?

A: パフォーマンス改善設定:

{
    "editor.formatOnSaveTimeout": 2000,
    "typescript.preferences.maxTsServerMemory": 4096,
    "files.watcherExclude": {
        "**/node_modules/**": true
    }
}

まとめ

VS Codeでインデントを整形する方法をまとめると:

基本操作

  • Shift + Alt + F で手動整形
  • "editor.formatOnSave": true で保存時自動整形
  • "editor.tabSize": 2 などでインデント幅を統一

より高度な設定

  • 言語別の細かなカスタマイズで最適化
  • Prettier、ESLint などの外部ツール連携
  • EditorConfig でプロジェクト横断的な統一
  • チーム開発向けの設定共有

コメント

タイトルとURLをコピーしました