Minimal AlpineJS wrapper for twMerge and clsx. magic and directive for Alpine.js
npm install alpinejs-twmergex-twmergeAlpine JS plugin x-twmerge is a minimal wrapper designed to integrate twMerge and clsx with AlpineJS, offering both a directive x-twmerge for dynamic class management and a magic method $twMerge for computed class merging. This plugin enables you to leverage the utility-first CSS approach of Tailwind CSS dynamically within your Alpine.js components.
- x-twmerge Directive: Dynamically apply and manage Tailwind CSS classes based on component state.
- $twMerge Magic Method: Use this magic method to compute and merge classes programmatically within Alpine.js expressions.
x-twmerge BehaviorWhen x-twmerge is initialized on an element, it takes note of the original classes defined on that element and always uses them as the base/first set of classes sent to twMerge. This ensures that the initial styling of the element is preserved, and only the additional dynamic classes are merged or toggled based on component state.
Example of x-twmerge preserving original classes:
``html`
In contrast, the $twMerge magic method does not automatically include the element's original classes. It only processes the classes provided to it and returns the merged class string. All the dynamic classes need to be sent to the $twMerge magic in order for it to correctly merge them as it does not know the element original classes.
Example of $twMerge without preserving original classes:
`html`
Toggle a class based on component state using the x-twmerge directive:
`html`
Pass an array of classes to x-twmerge:
`html`
Utilize a clsx-like object syntax with x-twmerge for more complex class logic:
`html
x-twmerge="{
'text-white': true,
'bg-red-500': error,
'bg-yellow-500': warning && !error,
}">
$3
Use
$twMerge within the :class binding for computed class strings:`html
:class="$twMerge([
'text-base',
'font-semibold',
primary ? 'text-blue-500' : 'text-gray-800',
secondary && 'bg-yellow-200'
])">
Installation
$3
`html
`$3
`shell
npm i -D alpinejs-twmerge
or
yarn add -D alpinejs-twmerge
`Then, integrate it into your project:
`js
import Alpine from "alpinejs";
import twmerge from "alpinejs-twmerge";Alpine.plugin(twmerge);
window.Alpine = Alpine;
Alpine.start();
``



