Skip to content

Tailwind:Plugins

재사용 가능한 타사 플러그인으로 Tailwind를 확장합니다. ​

개요

플러그인을 사용하면 CSS 대신 JavaScript를 사용하여 Tailwind에 새로운 스타일을 등록하여 사용자의 스타일시트에 삽입할 수 있습니다.

Usage

첫 번째 플러그인 을 시작하려면 tailwindcss/pluginplugin 함수를 import 한다.

그런 다음 배열 내에서 익명 함수를 첫 번째 인수를 사용.

const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function({ addUtilities, addComponents, e, config }) {
      // Add your custom styles here
    }),
  ]
}

플러그인 함수는 여러 도우미 함수로 구조화 될 수 있는 단일 개체 인수를 받습니다 .

  • #addUtilities - 새로운 정적 유틸리티 스타일 등록용
  • #matchUtilities - 새로운 동적 유틸리티 스타일 등록용
  • #addComponents - 새로운 정적 구성요소 스타일 등록용
  • #matchComponents - 새로운 동적 구성요소 스타일 등록용
  • #addBase - 새 기본 스타일 등록용
  • #addVariant - 사용자 정의 정적 변형 등록용
  • #matchVariant - 맞춤 동적 변형 등록용
  • #theme - 사용자의 테마 구성에서 값을 조회하기 위한 것입니다.
  • #config - 사용자의 Tailwind 구성에서 값 조회용
  • #corePlugins - 핵심 플러그인이 활성화되어 있는지 확인하기 위해
  • #e - 클래스 이름에 사용되는 문자열을 수동으로 이스케이프하는 경우

공식 플러그인

우리는 어떤 이유로든 아직 핵심에 속하지 않는 인기 기능을 위한 몇 가지 공식 플러그인을 개발했습니다.

npm을 통해 플러그인을 설치한 후 파일에 추가하면 프로젝트에 플러그인을 추가할 수 있습니다

tailwind.config.js:

/** @type {import('tailwindcss').Config} */
module.exports = {
  // ...
  plugins: [
    require('@tailwindcss/typography'),
    require('@tailwindcss/forms'),
    require('@tailwindcss/aspect-ratio'),
    require('@tailwindcss/container-queries'),
  ]
}

Typography

플러그인 은 마크다운이나 CMS 데이터베이스와 같은 소스에서 가져온 콘텐츠 블록에 합리적인 인쇄 스타일을 빠르게 추가하는 데 사용할 수 있다.

<article class="prose lg:prose-xl">
  <h1>Garlic bread with cheese: What the science tells us</h1>
  <p>
    For years parents have espoused the health benefits of eating garlic bread with cheese to their
    children, with the food earning such an iconic status in our culture that kids will often dress
    up as warm, cheesy loaf for Halloween.
  </p>
  <p>
    But a recent study shows that the celebrated appetizer may be linked to a series of rabies cases
    springing up around the country.
  </p>
  <!-- ... -->
</article>

Forms

양식 요소의 스타일을 더 쉽게 지정할 수 있는 독창적인 양식 재설정 레이어를 추가합니다.

<!-- You can actually customize padding on a select element: -->
<select class="px-4 py-3 rounded-full">
  <!-- ... -->
</select>

<!-- Or change a checkbox color using text color utilities: -->
<input type="checkbox" class="rounded text-pink-500" />

Aspect ratio

요소에 고정된 종횡비를 제공하기 위해 결합할 수 있는 추가 및 클래스입니다.

<div class="aspect-w-16 aspect-h-9">
  <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

Container queries

뷰포트 대신에 표시된 상위 요소의 크기를 기반으로 요소의 스타일을 지정할 수 있다.

<div class="@container">
  <div class="@lg:text-sky-400">
    <!-- ... -->
  </div>
</div>

APIs

addUtilities

matchUtilities

import plugin from 'tailwindcss/plugin';

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      textShadow: {
        xs: '0 1px 2px var(--tw-shadow-color)',
        sm: '0 2px 4px var(--tw-shadow-color)',
        base: '0 4px 8px var(--tw-shadow-color)',
        md: '0 8px 16px var(--tw-shadow-color)',
        lg: '0 12px 24px var(--tw-shadow-color)',
      },
    },
  },
  plugins: [
    plugin(function ({ matchUtilities, theme }) {
      matchUtilities(
        {
          'text-shadow': (value) => ({
            textShadow: value,
          }),
        },
        { values: theme('textShadow') }
      )
    }),
  ],
}

addComponents

matchComponents

addBase

addVariant

matchVariant

theme

config

corePlugins

e

Color Extend

다음과 같이 사용하면 @apply bg-primary/2 와 같이 alpha 값을 추가할 때 <alpha-value> 가 치환된다:

/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    colors: {
      // Using modern `rgb`
      primary: 'rgb(var(--color-primary) / <alpha-value>)',
      secondary: 'rgb(var(--color-secondary) / <alpha-value>)',

      // Using modern `hsl`
      primary: 'hsl(var(--color-primary) / <alpha-value>)',
      secondary: 'hsl(var(--color-secondary) / <alpha-value>)',

      // Using legacy `rgba`
      primary: 'rgba(var(--color-primary), <alpha-value>)',
      secondary: 'rgba(var(--color-secondary), <alpha-value>)',
    }
  }
}

<alpha-value> 가 적용되지 않는 문제

interestingly, theme(), "theme()" and @apply will all generate different values:

see https://play.tailwindcss.com/fX0CEoXvGu

addUtilities({
  '.test': {
    color: theme('colors.primary.DEFAULT'),
    background: 'theme("colors.primary.DEFAULT")',
    '@apply border-primary': '',
  },
})

will generate:

.test {
    color: rgb(var(--primary) / <alpha-value>);
    background: rgb(var(--primary) / 1);
    --tw-border-opacity: 1;
    border-color: rgb(var(--primary) / var(--tw-border-opacity));
}

looks like only @apply does the correct thing currently?

Example

const colCount = plugin(
  function ({addUtilities, theme, e}) {
    const values = theme('colCount')
    var utilities = Object.entries(values).map(([key, value]) => {
      return {
        [`.${e(`col-count-${key}`)}`]: {columnCount: `${value}`},
      }
    })
    addUtilities(utilities)
  },
  {
    theme: {
      colCount: {
        2: '2',
        3: '3',
        4: '4',
        5: '5',
        6: '6',
      },
    },
  },
)
module.exports = colCount

스크랩분류에 사용한 테마 플러그인

/** @type {import('tailwindcss/plugin').Plugin} */
const plugin = require('tailwindcss/plugin');

const rallyColors = { ... };

const rallyTheme = plugin(({theme}) => {}, {
  theme: {
    extend: {
      fontFamily: {
        sans: ['Noto Sans KR', 'sans-serif', 'system-ui'],
        serif: ['serif', 'system-ui'],
        mono: ['monospace', 'system-ui'],
      },
      colors: {
        background: '#36363F',
        foreground: '#FFFFFF',
        header: '#2b2b32',

        primary: rallyColors.green['500'],
        secondary: rallyColors.teal['700'],
        tertiary: rallyColors.orange['300'],
        quaternary: rallyColors.yellow['300'],
        quinary: rallyColors.purple['200'],
        senary: rallyColors.blue['200'],

        error: '#B00020',
        warning: '#FB8C00',
        info: '#2196F3',
        success: '#4CAF50',

        ...rallyColors,
      },
      spacing: {
        topbar: '2.5rem',
      },
    },
  },
});

module.exports = rallyTheme;

그리고 tailwind.config.js에서 다음과 같이 사용함:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  plugins: [require('./tailwind.plugin.rally')],
};

See also

Favorite site