Tailwind CSS Academy · 강의

클래스 정렬과 Prettier 플러그인

prettier-plugin-tailwindcss를 설치하여 유틸리티 클래스를 표준 순서로 자동 정렬하고 가독성을 높이며 병합 충돌을 줄입니다.

레슨 2/413개 단계

클래스 정렬과 Prettier 플러그인은(는) CoddyKit의 무료 Tailwind CSS Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Tailwind CSS Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Class Order Matters

When multiple Tailwind developers work on the same project, utility classes inevitably appear in different orders in different files. While class order rarely affects rendering, inconsistent ordering makes code reviews noisy and diff outputs hard to read. A consistent canonical order helps everyone understand component structure at a glance.

Introducing prettier-plugin-tailwindcss

prettier-plugin-tailwindcss is the official Tailwind CSS Prettier plugin maintained by the Tailwind team. It automatically sorts utility classes in your markup into a canonical order every time Prettier formats a file. No manual effort is needed — just save and the classes reorganize themselves.

npm install -D prettier prettier-plugin-tailwindcss

Configuring the Plugin

After installation, add the plugin to your Prettier configuration file. The plugin works automatically with no extra options required for most projects. If your tailwind.config.js is in a non-standard location, point Prettier to it with the tailwindConfig option.

// .prettierrc
{
  "plugins": ["prettier-plugin-tailwindcss"],
  "tailwindConfig": "./tailwind.config.js"
}

The Canonical Sorting Order

The plugin sorts classes following Tailwind's recommended order: layout utilities first (display, position, overflow), then box model (width, height, padding, margin), then typography, then visual properties (background, border, shadow), and finally interactive states and responsive variants. This reflects how CSS specificity cascades.

<!-- BEFORE sorting -->
<div class="text-white hover:bg-blue-700 p-4 rounded-lg bg-blue-500 flex items-center gap-2">

<!-- AFTER prettier-plugin-tailwindcss sorts -->
<div class="flex items-center gap-2 rounded-lg bg-blue-500 p-4 text-white hover:bg-blue-700">

Running Prettier on Your Project

Once configured, run Prettier across all your template files to apply sorting in bulk. Add a format script to your package.json for easy access. Developers should run this before every commit, or better yet, wire it into a pre-commit hook with Husky.

// package.json
{
  "scripts": {
    "format": "prettier --write \"src/**/*.{html,jsx,tsx,vue}\"",
    "format:check": "prettier --check \"src/**/*.{html,jsx,tsx,vue}\""
  }
}

Editor Integration

For the best developer experience, configure your editor to format on save. In VS Code, install the Prettier extension and set editor.formatOnSave: true in your settings. This means classes sort automatically whenever you save a file, keeping your markup tidy without any extra steps.

// .vscode/settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[html]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Pre-Commit Hook With Husky

Automating formatting at commit time with Husky and lint-staged ensures no unsorted classes ever enter the repository. When a developer commits, only the staged files are formatted and re-staged — a fast, focused operation even in large projects.

npm install -D husky lint-staged
npx husky init

// package.json
{
  "lint-staged": {
    "*.{html,jsx,tsx,vue}": "prettier --write"
  }
}

Sorting in JSX and TSX Files

The plugin handles JSX and TSX files too, sorting classes inside className attributes and string arguments to utilities like clsx and tailwind-merge. It uses static analysis to find class strings, so dynamically constructed strings are left unchanged — only static string literals are sorted.

// Before
const Button = () => (
  <button className="font-semibold text-white hover:bg-blue-700 rounded bg-blue-500 px-4 py-2">
    Click me
  </button>
);

// After sorting
const Button = () => (
  <button className="rounded bg-blue-500 px-4 py-2 font-semibold text-white hover:bg-blue-700">
    Click me
  </button>
);

Sorting in Template Literals and clsx

The plugin recognizes class strings passed to popular helpers like clsx, cn, and tailwind-merge when called with string arguments. This means your conditional class logic stays sorted even when spread across multiple arguments, keeping composition patterns clean and readable.

import { clsx } from 'clsx';

// The plugin sorts string arguments inside clsx calls
const classes = clsx(
  'rounded bg-blue-500 px-4 py-2 text-white',
  isActive && 'ring-2 ring-blue-300',
  isDisabled && 'cursor-not-allowed opacity-50'
);

CI Enforcement With Prettier Check

Add Prettier's --check mode to your CI pipeline to fail builds when files contain unsorted classes. This ensures that even if a developer skips the pre-commit hook, unsorted code never merges into main. The check exits with a non-zero status code when formatting differences are found.

# .github/workflows/ci.yml
jobs:
  format-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm run format:check

Handling Edge Cases and Custom Classes

The plugin sorts known Tailwind classes but leaves unrecognized class names in place at the end. If you use custom utilities added via plugins, configure the tailwindConfig option so the plugin is aware of them. Custom classes that the plugin cannot identify will still appear but will not break the sort of recognized utilities.

// .prettierrc — point to config so custom utilities are recognized
{
  "plugins": ["prettier-plugin-tailwindcss"],
  "tailwindConfig": "./tailwind.config.js"
}

// tailwind.config.js — custom utility plugin
plugins: [
  plugin(({ addUtilities }) => {
    addUtilities({ '.text-shadow': { 'text-shadow': '2px 2px 4px rgba(0,0,0,0.5)' } });
  }),
],

Quick Check

Test your understanding of Tailwind CSS Mastery concepts from this lesson.

Lesson Recap

In this lesson you learned: installing and configuring prettier-plugin-tailwindcss to automate class sorting, integrating with editor format-on-save for a seamless workflow, and enforcing sorted classes in CI with Prettier's check mode. Next up we explore linting Tailwind with ESLint.

무료로 시작

AI 튜터와 함께 HTML을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
30
레슨
120

자주 묻는 질문

“클래스 정렬과 Prettier 플러그인” 강의는 무료인가요?

네 — “클래스 정렬과 Prettier 플러그인” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Tailwind CSS Academy 강의 전체를 잠금 해제할 수 있습니다. Tailwind CSS Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“클래스 정렬과 Prettier 플러그인”에서 뭘 배우나요?

prettier-plugin-tailwindcss를 설치하여 유틸리티 클래스를 표준 순서로 자동 정렬하고 가독성을 높이며 병합 충돌을 줄입니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Tailwind CSS Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Tailwind CSS Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“클래스 정렬과 Prettier 플러그인” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Tailwind CSS Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Tailwind CSS Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. CSS 출력 점검
  2. 클래스 정렬과 Prettier 플러그인
  3. ESLint로 Tailwind 린트하기
  4. 팀 규칙과 스타일 가이드
← Tailwind CSS Academy(으)로 돌아가기