A Prettier v3+ plugin for Tailwind CSS v3.0+ that automatically sorts classes based on our recommended class order.
To get started, install prettier-plugin-tailwindcss
as a dev-dependency:
npm install -D prettier prettier-plugin-tailwindcss
Then add the plugin to your Prettier config:
// prettier.config.js
module.exports = {
plugins: ['prettier-plugin-tailwindcss'],
}
As of v0.5.x, this plugin now requires Prettier v3 and is ESM-only. This means it cannot be loaded via require()
. For more information see our upgrade guide.
To ensure that the class sorting takes into consideration any of your project's Tailwind customizations, it needs access to your Tailwind configuration file (tailwind.config.js
).
By default the plugin will look for this file in the same directory as your Prettier configuration file. However, if your Tailwind configuration is somewhere else, you can specify this using the tailwindConfig
option in your Prettier configuration.
Note that paths are resolved relative to the Prettier configuration file.
// prettier.config.js
module.exports = {
tailwindConfig: './styles/tailwind.config.js',
}
If a local configuration file cannot be found the plugin will fallback to the default Tailwind configuration.
By default this plugin only sorts classes in the class
attribute as well as any framework-specific equivalents like class
, className
, :class
, [ngClass]
, etc.
You can sort additional attributes using the tailwindAttributes
option, which takes an array of attribute names:
// prettier.config.js
module.exports = {
tailwindAttributes: ['myClassList'],
}
With this configuration, any classes found in the myClassList
attribute will be sorted:
function MyButton({ children }) {
return (
<button myClassList="rounded bg-blue-500 px-4 py-2 text-base text-white">
{children}
</button>
);
}
In addition to sorting classes in attributes, you can also sort classes in strings provided to function calls. This is useful when working with libraries like clsx or cva.
You can sort classes in function calls using the tailwindFunctions
option, which takes a list of function names:
// prettier.config.js
module.exports = {
tailwindFunctions: ['clsx'],
}
With this configuration, any classes in clsx()
function calls will be sorted:
import clsx from 'clsx'
function MyButton({ isHovering, children }) {
let classes = clsx(
'rounded bg-blue-500 px-4 py-2 text-base text-white',
{
'bg-blue-700 text-gray-100': isHovering,
},
)
return (
<button className={classes}>
{children}
</button>
)
}
This plugin also enables sorting of classes in tagged template literals.
You can sort classes in template literals using the tailwindFunctions
option, which takes a list of function names:
// prettier.config.js
module.exports = {
tailwindFunctions: ['tw'],
}