Writing Plugins

Extending Tailwind with reusable third-party plugins.


Overview

At their simplest, plugins are just functions that register new styles for Tailwind to inject into the user’s stylesheet. That means that to get started authoring your own plugin, all you need to do is add an anonymous function to the plugins list in your config file:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addUtilities, addComponents, e, prefix, config }) {
  5. // This function is your plugin
  6. },
  7. ]
  8. }

Plugin functions receive a single object argument that can be destructured into several helper functions:

  • addUtilities(), for registering new utility styles
  • addComponents(), for registering new component styles
  • addBase(), for registering new base styles
  • addVariant(), for registering custom variants
  • e(), for escaping strings meant to be used in class names
  • prefix(), for manually applying the user’s configured prefix to parts of a selector
  • theme(), for looking up values in the user’s theme configuration
  • variants(), for looking up values in the user’s variants configuration
  • config(), for looking up values in the user’s Tailwind configuration

Adding utilities

The addUtilities function allows you to register new styles to be output (along with the built-in utilities) at the @tailwind utilities directive.

Plugin utilities are output in the order they are registered, after built-in utilities, so if a plugin targets any of the same properties as a built-in utility, the plugin utility will take precedence.

To add new utilities from a plugin, call addUtilities, passing in your styles using CSS-in-JS syntax:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addUtilities }) {
  5. const newUtilities = {
  6. '.skew-10deg': {
  7. transform: 'skewY(-10deg)',
  8. },
  9. '.skew-15deg': {
  10. transform: 'skewY(-15deg)',
  11. },
  12. }
  13. addUtilities(newUtilities)
  14. }
  15. ]
  16. }

Prefix and important preferences

By default, plugin utilities automatically respect the user’s prefix and important preferences.

That means that given this Tailwind configuration:

  1. // tailwind.config.js
  2. module.exports = {
  3. prefix: 'tw-',
  4. important: true,
  5. // ...
  6. }

…the example plugin above would generate the following CSS:

  1. .tw-skew-10deg {
  2. transform: skewY(-10deg) !important;
  3. }
  4. .tw-skew-15deg {
  5. transform: skewY(-15deg) !important;
  6. }

If necessary, you can opt out of this behavior by passing an options object as a second parameter to addUtilities:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addUtilities }) {
  5. const newUtilities = {
  6. // ...
  7. }
  8. addUtilities(newUtilities, {
  9. respectPrefix: false,
  10. respectImportant: false,
  11. })
  12. }
  13. ]
  14. }

Responsive and pseudo-class variants

To generate responsive, hover, focus, active, or group-hover variants of your styles, specify the variants you’d like to generate using the variants option:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addUtilities }) {
  5. const newUtilities = {
  6. // ...
  7. }
  8. addUtilities(newUtilities, {
  9. variants: ['responsive', 'hover'],
  10. })
  11. }
  12. ]
  13. }

If you only need to specify variants and don’t need to opt-out of the default prefix or important options, you can also pass the array of variants as the second parameter directly:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addUtilities }) {
  5. const newUtilities = {
  6. // ...
  7. }
  8. addUtilities(newUtilities, ['responsive', 'hover'])
  9. }
  10. ]
  11. }

If you’d like the user to provide the variants themselves under the variants section in their tailwind.config.js file, you can use the variants() function to get the variants they have configured:

  1. // tailwind.config.js
  2. module.exports = {
  3. variants: {
  4. customPlugin: ['responsive', 'hover'],
  5. },
  6. plugins: [
  7. function({ addUtilities, variants }) {
  8. const newUtilities = {
  9. // ...
  10. }
  11. addUtilities(newUtilities, variants('customPlugin'))
  12. }
  13. ]
  14. }

Adding components

The addComponents function allows you to register new styles to be output at the @tailwind components directive.

Use it to add more opinionated, complex classes like buttons, form controls, alerts, etc; the sort of pre-built components you often see in other frameworks that you might need to override with utility classes.

To add new component styles from a plugin, call addComponents, passing in your styles using CSS-in-JS syntax:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addComponents }) {
  5. const buttons = {
  6. '.btn': {
  7. padding: '.5rem 1rem',
  8. borderRadius: '.25rem',
  9. fontWeight: '600',
  10. },
  11. '.btn-blue': {
  12. backgroundColor: '#3490dc',
  13. color: '#fff',
  14. '&:hover': {
  15. backgroundColor: '#2779bd'
  16. },
  17. },
  18. '.btn-red': {
  19. backgroundColor: '#e3342f',
  20. color: '#fff',
  21. '&:hover': {
  22. backgroundColor: '#cc1f1a'
  23. },
  24. },
  25. }
  26. addComponents(buttons)
  27. }
  28. ]
  29. }

Prefix and important preferences

By default, component classes automatically respect the user’s prefix preference, but they are not affected by the user’s important preference.

That means that given this Tailwind configuration:

  1. // tailwind.config.js
  2. module.exports = {
  3. prefix: 'tw-',
  4. important: true,
  5. // ...
  6. }

…the example plugin above would generate the following CSS:

  1. .tw-btn {
  2. padding: .5rem 1rem;
  3. border-radius: .25rem;
  4. font-weight: 600;
  5. }
  6. .tw-btn-blue {
  7. background-color: #3490dc;
  8. color: #fff;
  9. }
  10. .tw-btn-blue:hover {
  11. background-color: #2779bd;
  12. }
  13. .tw-btn-blue {
  14. background-color: #e3342f;
  15. color: #fff;
  16. }
  17. .tw-btn-blue:hover {
  18. background-color: #cc1f1a;
  19. }

Although there’s rarely a good reason to make component declarations important, if you really need to do it you can always add !important manually:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addComponents }) {
  5. const buttons = {
  6. '.btn': {
  7. padding: '.5rem 1rem !important',
  8. borderRadius: '.25rem !important',
  9. fontWeight: '600 !important',
  10. },
  11. // ...
  12. }
  13. addComponents(buttons)
  14. }
  15. ]
  16. }

All classes in a selector will be prefixed by default, so if you add a more complex style like:

  1. // tailwind.config.js
  2. module.exports = {
  3. prefix: 'tw-',
  4. plugins: [
  5. function({ addComponents }) {
  6. const components = {
  7. // ...
  8. '.navbar-inverse a.nav-link': {
  9. color: '#fff',
  10. }
  11. }
  12. addComponents(components)
  13. }
  14. ]
  15. }

…the following CSS would be generated:

  1. .tw-navbar-inverse a.tw-nav-link {
  2. color: #fff;
  3. }

To opt out of prefixing, pass an options object as a second parameter to addComponents:

  1. // tailwind.config.js
  2. module.exports = {
  3. prefix: 'tw-',
  4. plugins: [
  5. function({ addComponents }) {
  6. const components = {
  7. // ...
  8. }
  9. addComponents(components, {
  10. respectPrefix: false
  11. })
  12. }
  13. ]
  14. }

Responsive and pseudo-class variants

The addComponents function doesn’t provide the ability to automatically generate variants since it doesn’t typically make sense to do so for component classes.

You can always do this manually if necessary by wrapping your styles in the @variants at-rule:

  1. function({ addComponents }) {
  2. addComponents({
  3. '@variants responsive, hover': {
  4. '.btn': {
  5. padding: '.5rem 1rem !important',
  6. borderRadius: '.25rem !important',
  7. fontWeight: '600 !important',
  8. },
  9. // ...
  10. }
  11. })
  12. }

Adding base styles

The addBase function allows you to register new styles to be output at the @tailwind base directive.

Use it to add things like base typography styles, opinionated global resets, or @font-face rules.

To add new component styles from a plugin, call addBase, passing in your styles using CSS-in-JS syntax:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addComponents }) {
  5. addBase({
  6. 'h1': { fontSize: config('theme.fontSize.2xl') },
  7. 'h2': { fontSize: config('theme.fontSize.xl') },
  8. 'h3': { fontSize: config('theme.fontSize.lg') },
  9. })
  10. }
  11. ]
  12. }

Since base styles are meant to target bare selectors like div, h1, etc., they do not respect the user’s prefix or important configuration.


Escaping class names

If your plugin generates classes that contain user-provided strings, you can use the e function to escape those class names to make sure non-standard characters are handled properly automatically.

For example, this plugin generates a set of .rotate-{angle} utilities where {angle} is a user provided string. The e function is used to escape the concatenated class name to make sure classes like .rotate-1/4 work as expected:

  1. // tailwind.config.js
  2. const _ = require('lodash')
  3. module.exports = {
  4. theme: {
  5. rotate: {
  6. '1/4': '90deg',
  7. '1/2': '180deg',
  8. '3/4': '270deg',
  9. }
  10. },
  11. plugins: [
  12. function({ addUtilities, config, e }) {
  13. const rotateUtilities = _.map(config('theme.rotate'), (value, key) => {
  14. return {
  15. [`.${e(`rotate-${key}`)}`]: {
  16. transform: `rotate(${value})`
  17. }
  18. }
  19. })
  20. addUtilities(rotateUtilities)
  21. }
  22. ]
  23. }

This plugin would generate the following CSS:

  1. .rotate-1\/4 {
  2. transform: rotate(90deg);
  3. }
  4. .rotate-1\/2 {
  5. transform: rotate(180deg);
  6. }
  7. .rotate-3\/4 {
  8. transform: rotate(270deg);
  9. }

Be careful to only escape content you actually want to escape; don’t pass the leading . in a class name or the : at the beginning pseudo-classes like :hover or :focus or those characters will be escaped.

Additionally, because CSS has rules about the characters a class name can start with (a class can’t start with a number, but it can contain one), it’s a good idea to escape your complete class name (not just the user-provided portion) or you may end up with unnecessary escape sequences:

  1. // Will unnecessarily escape `1`
  2. `.rotate-${e('1/4')}`
  3. // => '.rotate-\31 \/4'
  4. // Won't escape `1` because it's not the first character
  5. `.${e('rotate-1/4')}`
  6. // => '.rotate-1\/4'

Manually prefixing selectors

If you’re writing something complex where you only want to prefix certain classes, you can use the prefix function to have fine-grained control of when the user’s configured prefix is applied.

For example, if you’re creating a plugin to be reused across a set of internal projects that includes existing classes in its selectors, you might only want to prefix the new classes:

  1. // tailwind.config.js
  2. module.exports = {
  3. prefix: 'tw-',
  4. plugins: [
  5. function({ addComponents, prefix }) {
  6. addComponents({
  7. [`.existing-class > ${prefix('.new-class')}`]: {
  8. backgroundColor: '#fff',
  9. }
  10. })
  11. }
  12. ]
  13. }

This would generate the following CSS:

  1. .existing-class > .tw-new-class {
  2. background-color: #fff;
  3. }

The prefix function will prefix all classes in a selector and ignore non-classes, so it’s totally safe to pass complex selectors like this one:

  1. prefix('.btn-blue .w-1\/4 > h1.text-xl + a .bar')
  2. // => '.tw-btn-blue .tw-w-1\/4 > h1.tw-text-xl + a .tw-bar'

Referencing the user’s config

The config, theme, and variants functions allow you to ask for a value from the user’s Tailwind configuration using dot notation, providing a default value if that path doesn’t exist.

For example, this simplified version of the built-in container plugin uses the theme function to get the user’s configured breakpoints:

  1. // tailwind.config.js
  2. const _ = require('lodash')
  3. module.exports = {
  4. plugins: [
  5. function({ addComponents, theme }) {
  6. const screens = theme('screens', {})
  7. const mediaQueries = _.map(screens, width => {
  8. return {
  9. [`@media (min-width: ${width})`]: {
  10. '.container': {
  11. 'max-width': width,
  12. },
  13. },
  14. }
  15. })
  16. addComponents([
  17. { '.container': { width: '100%' } },
  18. ...mediaQueries,
  19. ])
  20. }
  21. ]
  22. }

Note that the theme function is really just a shortcut for using the config function to access the theme section of the user’s config:

  1. // These are equivalent
  2. config('theme.screens')
  3. theme('screens')

If you’d like to reference the user’s variants configuration, it’s recommended that you use the variants() function instead of the config function.

Writing Plugins - 图1Don’t use the config function to look up variants

  1. addUtilities(newUtilities, config('variants.customPlugin'))

Writing Plugins - 图2Use unprefixed utilities to target mobile, and override them at larger breakpoints

  1. addUtilities(newUtilities, variants('customPlugin'))

Since variants could simply be a global list of variants to configure for every plugin in the whole project, using the variants() function lets you easily respect the user’s configuration without reimplementing that logic yourself.

  1. // tailwind.config.js
  2. module.exports = {
  3. variants: ['responsive', 'hover', 'focus'],
  4. plugins: [
  5. function ({ config, variants }) {
  6. config('variants.customPlugin')
  7. // => undefined
  8. variants('customPlugin')
  9. // => ['reponsive', 'hover', 'focus']
  10. }
  11. ]
  12. }

Exposing options

It often makes sense for a plugin to expose its own options that the user can configure to customize the plugin’s behavior.

The best way to accomplish this is to claim your own key in the user’s theme and variants configuration and ask them to provide any options there so you can access them with the theme and variants functions.

For example, here’s a plugin (extracted to its own module) for creating simple gradient utilities that accepts the gradients and variants to generate as options:

  1. // ./plugins/gradients.js
  2. const _ = require('lodash')
  3. module.exports = function({ addUtilities, e, theme, variants }) {
  4. const gradients = theme('gradients', {})
  5. const gradientVariants = variants('gradients', [])
  6. const utilities = _.map(gradients, ([start, end], name) => ({
  7. [`.bg-gradient-${e(name)}`]: {
  8. backgroundImage: `linear-gradient(to right, ${start}, ${end})`
  9. }
  10. }))
  11. addUtilities(utilities, gradientVariants)
  12. }

To use it, you’d require it in your plugins list, specifying your configuration under the gradients key in both theme and variants:

  1. // tailwind.config.js
  2. module.exports = {
  3. theme: {
  4. gradients: theme => ({
  5. 'blue-green': [theme('colors.blue.500'), theme('colors.green.500')],
  6. 'purple-blue': [theme('colors.purple.500'), theme('colors.blue.500')],
  7. // ...
  8. })
  9. },
  10. variants: {
  11. gradients: ['responsive', 'hover'],
  12. },
  13. plugins: [
  14. require('./plugins/gradients')
  15. ],
  16. }

CSS-in-JS syntax

Each of addUtilities, addComponents, and addBase expect CSS rules written as JavaScript objects. Tailwind uses the same sort of syntax you might recognize from CSS-in-JS libraries like Emotion, and is powered by postcss-js under the hood.

Consider this simple CSS rule:

  1. .card {
  2. background-color: #fff;
  3. border-radius: .25rem;
  4. box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  5. }

Translating this to a CSS-in-JS object would look like this:

  1. addComponents({
  2. '.card': {
  3. 'background-color': '#fff',
  4. 'border-radius': '.25rem',
  5. 'box-shadow': '0 2px 4px rgba(0,0,0,0.2)',
  6. }
  7. })

For convenience, property names can also be written in camelCase and will be automatically translated to dash-case:

  1. addComponents({
  2. '.card': {
  3. backgroundColor: '#fff',
  4. borderRadius: '.25rem',
  5. boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  6. }
  7. })

Nesting is also supported (powered by postcss-nested), using the same syntax you might be familiar with from Sass or Less:

  1. addComponents({
  2. '.card': {
  3. backgroundColor: '#fff',
  4. borderRadius: '.25rem',
  5. boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
  6. '&:hover': {
  7. boxShadow: '0 10px 15px rgba(0,0,0,0.2)',
  8. }
  9. '@media (min-width: 500px)': {
  10. borderRadius: '.5rem',
  11. }
  12. }
  13. })

Multiple rules can be defined in the same object:

  1. addComponents({
  2. '.btn': {
  3. padding: '.5rem 1rem',
  4. borderRadius: '.25rem',
  5. fontWeight: '600',
  6. },
  7. '.btn-blue': {
  8. backgroundColor: '#3490dc',
  9. color: '#fff',
  10. '&:hover': {
  11. backgroundColor: '#2779bd'
  12. },
  13. },
  14. '.btn-red': {
  15. backgroundColor: '#e3342f',
  16. color: '#fff',
  17. '&:hover': {
  18. backgroundColor: '#cc1f1a'
  19. },
  20. },
  21. })

…or as an array of objects in case you need to repeat the same key:

  1. addComponents([
  2. {
  3. '@media (min-width: 500px)': {
  4. // ...
  5. }
  6. },
  7. {
  8. '@media (min-width: 500px)': {
  9. // ...
  10. }
  11. },
  12. {
  13. '@media (min-width: 500px)': {
  14. // ...
  15. }
  16. },
  17. ])

Adding variants

The addVariant function allows you to register your own custom variants that can be used just like the built-in hover, focus, active, etc. variants.

To add a new variant, call the addVariant function, passing in the name of your custom variant, and a callback that modifies the affected CSS rules as needed.

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addVariant, e }) {
  5. addVariant('disabled', ({ modifySelectors, separator }) => {
  6. modifySelectors(({ className }) => {
  7. return `.${e(`disabled${separator}${className}`)}:disabled`
  8. })
  9. })
  10. }
  11. ]
  12. }

The callback receives an object that can be destructured into the following parts:

  • modifySelectors, a helper function to simplify adding basic variants
  • separator, the user’s configured separator string
  • container, a PostCSS Container containing all of the rules the variant is being applied to, for creating complex variants

Basic variants

If you want to add a simple variant that only needs to change the selector, use the modifySelectors helper.

The modifySelectors helper accepts a function that receives an object that can be destructured into the following parts:

  • selector, the complete unmodified selector for the current rule
  • className, the class name of the current rule with the leading dot removedThe function you pass to modifySelectors should simply return the modified selector.

For example, a first-child variant plugin could be written like this:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addVariant, e }) {
  5. addVariant('first-child', ({ modifySelectors, separator }) => {
  6. modifySelectors(({ className }) => {
  7. return `.${e(`first-child${separator}${className}`)}:first-child`
  8. })
  9. })
  10. }
  11. ]
  12. }

Complex variants

If you need to do anything beyond simply modifying selectors (like changing the actual rule declarations, or wrapping the rules in another at-rule), you’ll need to use the container instance.

Using the container instance, you can traverse all of the rules within a given module or @variants block and manipulate them however you like using the standard PostCSS API.

For example, this plugin creates an important version of each affected utility by prepending the class with an exclamation mark and modifying each declaration to be important:

  1. // tailwind.config.js
  2. module.exports = {
  3. plugins: [
  4. function({ addVariant }) {
  5. addVariant('important', ({ container }) => {
  6. container.walkRules(rule => {
  7. rule.selector = `.\\!${rule.selector.slice(1)}`
  8. rule.walkDecls(decl => {
  9. decl.important = true
  10. })
  11. })
  12. })
  13. }
  14. ]
  15. }

This plugin takes all of the rules inside the container, wraps them in a @supports (display: grid) at-rule, and prefixes each rule with supports-grid:

  1. // tailwind.config.js
  2. const postcss = require('postcss')
  3. module.exports = {
  4. plugins: [
  5. function({ addVariant, e }) {
  6. addVariant('supports-grid', ({ container, separator }) => {
  7. const supportsRule = postcss.atRule({ name: 'supports', params: '(display: grid)' })
  8. supportsRule.append(container.nodes)
  9. container.append(supportsRule)
  10. supportsRule.walkRules(rule => {
  11. rule.selector = `.${e(`supports-grid${separator}${rule.selector.slice(1)}`)}`
  12. })
  13. })
  14. }
  15. ]
  16. }

To learn more about working with PostCSS directly, check out the PostCSS API documentation.

Using custom variants

Using custom variants is no different than using Tailwind’s built-in variants.

To use custom variants with Tailwind’s core plugins, add them to the variants section of your config file:

  1. // tailwind.config.js
  2. modules.exports = {
  3. variants: {
  4. borderWidths: ['responsive', 'hover', 'focus', 'first-child', 'disabled'],
  5. }
  6. }

To use custom variants with custom utilities in your own CSS, use the variants at-rule:

  1. @variants hover, first-child {
  2. .bg-cover-image {
  3. background-image: url('/path/to/image.jpg');
  4. }
  5. }

Example plugins

To check out a few example plugins, visit the plugin examples repository on GitHub.