0Pricing
Tailwind CSS Academy · 강의

Tailwind 플러그인 API

plugin() 함수 시그니처를 익히고 addUtilities, addComponents, addBase, addVariant 도우미에 접근하여 Tailwind의 출력을 확장합니다.

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

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

Why Write Tailwind Plugins?

Tailwind's built-in utilities cover the vast majority of CSS needs, but there are gaps. You might need a scrollbar-hide utility, a text-shadow family, or a custom variant like not-last:. Rather than writing raw CSS outside of Tailwind's system, plugins let you add these extensions using the same configuration-driven approach as the rest of Tailwind. Plugins keep your extensions discoverable, consistent, and configurable.

The plugin() Function

Tailwind plugins are registered in the plugins array of tailwind.config.js. Each plugin is defined using the plugin() function from the tailwindcss/plugin package. The function receives a callback that gets four helpers: addUtilities, addComponents, addBase, and addVariant. These helpers inject styles into Tailwind's layer system at the correct position in the generated CSS.

// tailwind.config.js
const plugin = require('tailwindcss/plugin');

module.exports = {
  content: ['./src/**/*.{html,js}'],
  theme: { extend: {} },
  plugins: [
    plugin(function({ addUtilities, addComponents, addBase, addVariant }) {
      // Your extension code here
    })
  ]
};

addUtilities: Adding Utility Classes

addUtilities injects new utility classes into Tailwind's utilities layer. Pass it an object where keys are CSS selector strings (starting with a dot) and values are CSS property objects. These utilities work exactly like built-in Tailwind utilities — they respond to responsive prefixes, hover variants, and JIT arbitrary values when configured correctly.

plugin(function({ addUtilities }) {
  addUtilities({
    '.scrollbar-hide': {
      '-ms-overflow-style': 'none',
      'scrollbar-width': 'none',
      '&::-webkit-scrollbar': {
        display: 'none'
      }
    },
    '.text-balance': {
      'text-wrap': 'balance'
    },
    '.content-auto': {
      'content-visibility': 'auto'
    }
  });
})

// Now usable in markup:
// <div class='scrollbar-hide overflow-auto h-64'>...
// <h1 class='text-balance text-4xl font-bold'>...

addComponents: Adding Component Classes

addComponents injects styles into the components layer, which sits between base styles and utilities. Component styles have lower specificity than utilities, so utility classes can always override them. Use addComponents for reusable multi-property component patterns like .btn, .card, or .badge — the equivalent of using @apply in CSS files, but expressed as a plugin.

plugin(function({ addComponents }) {
  addComponents({
    '.btn': {
      display: 'inline-flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '0.5rem 1rem',
      borderRadius: '0.5rem',
      fontWeight: '500',
      fontSize: '0.875rem',
      transitionProperty: 'color, background-color',
      transitionDuration: '150ms',
      cursor: 'pointer'
    },
    '.btn-primary': {
      backgroundColor: '#3b82f6',
      color: '#ffffff',
      '&:hover': {
        backgroundColor: '#1d4ed8'
      }
    }
  });
})

addBase: Adding Base Styles

addBase injects styles into the base layer, which is the lowest-specificity layer in Tailwind. Use it for CSS resets, default element styles, or globally applicable rules that should underlie all other styles. addBase is where you would set box-sizing behavior, set a default font, or style native HTML elements.

plugin(function({ addBase, theme }) {
  addBase({
    // Style all h1-h6 elements with a consistent font
    'h1, h2, h3, h4, h5, h6': {
      fontFamily: theme('fontFamily.heading'),
      fontWeight: theme('fontWeight.semibold'),
      lineHeight: theme('lineHeight.tight')
    },
    // Custom focus style for all focusable elements
    ':focus-visible': {
      outline: '2px solid ' + theme('colors.blue.500'),
      outlineOffset: '2px'
    },
    // Smooth scrolling for the whole page
    'html': {
      scrollBehavior: 'smooth'
    }
  });
})

Accessing the Theme in Plugins

Plugin callbacks receive a theme helper function that retrieves values from your Tailwind config. This lets you reference your design tokens inside plugin-generated CSS, keeping plugin output consistent with the rest of your design system. Use theme('colors.blue.500'), theme('spacing.4'), theme('fontFamily.sans'), and any other config path.

plugin(function({ addUtilities, theme }) {
  // Generate text-shadow utilities using spacing scale
  const shadows = {
    '.text-shadow-sm': {
      textShadow: '0 1px 2px ' + theme('colors.black/20')
    },
    '.text-shadow': {
      textShadow: '0 2px 4px ' + theme('colors.black/30')
    },
    '.text-shadow-lg': {
      textShadow: '0 8px 16px ' + theme('colors.black/40')
    },
    '.text-shadow-none': {
      textShadow: 'none'
    }
  };
  addUtilities(shadows);
})

Generating Utilities From Theme Values

A powerful pattern is generating utility classes programmatically from the theme's color palette, spacing scale, or any other config values. Use JavaScript object spreading and the theme() helper to iterate over your palette and generate multiple utilities at once. This is how Tailwind itself generates its hundreds of color utilities from a single color definition.

plugin(function({ addUtilities, theme }) {
  // Generate border-start-* utilities from the color palette
  const colors = theme('colors');
  const utilities = {};

  Object.entries(colors).forEach(([colorName, shades]) => {
    if (typeof shades === 'string') {
      utilities['.border-start-' + colorName] = {
        borderInlineStartColor: shades
      };
    } else {
      Object.entries(shades).forEach(([shade, value]) => {
        utilities['.border-start-' + colorName + '-' + shade] = {
          borderInlineStartColor: value
        };
      });
    }
  });

  addUtilities(utilities);
})

matchUtilities for Arbitrary Values

The matchUtilities helper creates utilities that support Tailwind's arbitrary value syntax — bracket notation like text-shadow-[0_2px_4px_rgba(0,0,0,0.3)]. When you use matchUtilities, users can supply any value within brackets, giving full flexibility while keeping the utility name consistent with your design system convention.

plugin(function({ matchUtilities, theme }) {
  matchUtilities(
    {
      'text-shadow': (value) => ({
        textShadow: value
      })
    },
    {
      // Values from the theme that appear as autocomplete suggestions
      values: theme('textShadow')
    }
  );
  // Usage: text-shadow-sm (from theme) or
  //        text-shadow-[0_4px_8px_rgba(0,0,0,0.5)] (arbitrary)
})

// tailwind.config.js theme extension:
theme: {
  textShadow: {
    sm: '0 1px 2px rgba(0,0,0,0.2)',
    DEFAULT: '0 2px 4px rgba(0,0,0,0.3)',
    lg: '0 8px 16px rgba(0,0,0,0.4)'
  }
}

Plugin Options With withOptions

When you want to share a plugin across projects with configurable behavior, use plugin.withOptions() to create a factory that accepts a configuration object. The outer function receives user options; the inner function receives Tailwind's helpers. Users can then call your plugin as a function with configuration, similar to how @tailwindcss/typography accepts options.

const plugin = require('tailwindcss/plugin');

// scrollbar plugin with options
const scrollbarPlugin = plugin.withOptions(function(options = {}) {
  return function({ addUtilities }) {
    const { width = '6px', track = '#f1f5f9', thumb = '#94a3b8' } = options;

    addUtilities({
      '.scrollbar-custom': {
        '&::-webkit-scrollbar': { width },
        '&::-webkit-scrollbar-track': { background: track },
        '&::-webkit-scrollbar-thumb': { background: thumb, borderRadius: '3px' }
      }
    });
  };
});

// tailwind.config.js usage:
plugins: [
  scrollbarPlugin({ width: '8px', thumb: '#3b82f6' })
]

Debugging Plugins

When a plugin utility does not appear in the output CSS, debug with these steps: verify the plugin is in the plugins array, check that the selector syntax is correct (must start with .), and confirm that a file in the content paths actually uses the class name (JIT only generates classes it detects). Run npx tailwindcss build with --content to inspect the output CSS directly.

# Debug: build CSS and inspect output
npx tailwindcss \
  --input src/input.css \
  --output dist/debug.css \
  --content 'src/**/*.html'

# Then check:
grep 'text-shadow' dist/debug.css

# If missing:
# 1. Is the class used in an HTML file in content paths?
# 2. Does the addUtilities selector start with '.'?
# 3. Is the plugin listed in tailwind.config.js plugins array?

# Safelist it temporarily to confirm plugin works:
safelist: ['text-shadow-lg']

Using Official Tailwind Plugins

Before writing a custom plugin, check the official Tailwind plugins. @tailwindcss/typography adds a prose class for styling HTML content (like markdown). @tailwindcss/forms normalizes form element styles across browsers. @tailwindcss/aspect-ratio (legacy) adds aspect ratio utilities. Install them via npm and add them to the plugins array with optional configuration.

npm install @tailwindcss/typography @tailwindcss/forms

// tailwind.config.js
plugins: [
  require('@tailwindcss/typography'),
  require('@tailwindcss/forms')({
    strategy: 'class'  // use .form-input etc. classes
  })
]

// Usage:
<article class='prose prose-lg prose-blue max-w-none'>
  {/* Beautifully styled HTML content */}
</article>

<input type='text' class='form-input rounded-lg border-gray-300' />

Quick Check

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

Lesson Recap

In this lesson you learned: plugin() is the entry point for all Tailwind extensions, addUtilities/addComponents/addBase inject into the correct CSS layer at the right specificity level, and matchUtilities enables arbitrary value support for custom utilities. Next up we build a practical custom utility plugin that adds scrollbar and text-shadow utilities.

자주 묻는 질문

“Tailwind 플러그인 API” 강의는 무료인가요?

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

“Tailwind 플러그인 API”에서 뭘 배우나요?

plugin() 함수 시그니처를 익히고 addUtilities, addComponents, addBase, addVariant 도우미에 접근하여 Tailwind의 출력을 확장합니다. 브라우저에서 직접 실행하는 실습 코드로 Tailwind CSS Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“Tailwind 플러그인 API” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Tailwind 플러그인 API
  2. 플러그인으로 사용자 지정 유틸리티 추가
  3. 플러그인으로 사용자 지정 변형 추가
  4. 플러그인 게시 및 재사용
← Tailwind CSS Academy(으)로 돌아가기