萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 格式化插件與編輯器美化指南:Prettier、VS Code 內建格式化、Brackets 擴展管理器實戰

為什麼需要格式化?

  • 統一團隊代碼風格,減少無意義 Diff。
  • 暴露嵌套錯誤 (未閉合標籤、錯誤嵌套)。
  • 提升可讀性,利於 Code Review 與維護。

主流方案對比

方案適用編輯器配置複雜度特點
Prettier (推薦)VS Code, WebStorm, Sublime, Vim, CLI低 (零配置可用)有觀點、統一風格、支援 HTML/CSS/JS/TS/JSON/MD/GraphQL/Vue/Svelte/Astro
VS Code 內建格式化VS Code零無需安裝、但選項少、不支援模板語法 (Vue/Svelte)
HTMLHint + Stylelint所有中側重 **檢查規則** 而非格式化,配合 Prettier 使用
Brackets Beautify / 擴展管理器Brackets低圖形化安裝、但 Brackets 已停止維護 (2021 年歸檔)

Prettier 實戰配置 (項目級統一)

// .prettierrc.json (項目根目錄)
{
  "printWidth": 120,          // 單行最大字符數
  "tabWidth": 2,              // 縮進 2 空格
  "useTabs": false,
  "singleQuote": true,        // JS 單引號,HTML 屬性雙引號 (Prettier 固定)
  "bracketSameLine": false,   // > 換行
  "htmlWhitespaceSensitivity": "css", // 嚴格保留 CSS white-space 影響的空白
  "endOfLine": "lf",          // 換行符 LF
  "embeddedLanguageFormatting": "auto" // 格式化內嵌 CSS/JS
}
// .prettierignore
dist/
build/
*.min.html
public/

VS Code 設置聯動

// .vscode/settings.json (提交倉庫,團隊共享)
{
  "editor.formatOnSave": true,                 // 保存自動格式化
  "editor.defaultFormatter": "esbenp.prettier-vscode", // 指定 Prettier
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "html.format.wrapLineLength": 120,           // 內建格式化備選
  "html.format.enable": false                  // 關閉內建,避免衝突
}

CI/CD 攔截未格式化代碼

# .github/workflows/format.yml
name: Format Check
on: [push, pull_request]
jobs:
  prettier:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20' }
      - run: npm ci
      - run: npx prettier --check .

Brackets 遺產:擴展管理器安裝 Beautify (僅歷史參考)

  1. 菜單 **文件 → 擴展管理器**。
  2. 搜索「Beautify」→ 安裝「Beautify (JS/HTML/CSS)」。
  3. 快捷鍵 `Ctrl+Shift+L` (Win) / `Cmd+Shift+L` (Mac) 格式化當前文件。

遷移建議:Brackets 官方已歸檔,建議遷移至 VS Code + Prettier,生態更活躍、長期維護有保障。

特殊場景:模板語言格式化

  • Vue (.vue):Prettier 內建支援 `