tailwind-cssleptos

Custom tailwind class pattern matcher for Leptos


In rust Leptos framework, attributes can be defined as follows. Syntax is

<attribute>:<class_name>=<boolean>

If the boolean is true, class name will be added to the existing list. Here, tailwind cli by default identify the class="ease-in-out transition-all duration-1000" attribute as CSS classes and successfully generates it to the output CSS file.

However, it's not capturing any of class:<class_name> pattern. Is there a way to add custom match patterns in tailwind config?

<h1
  class="ease-in-out transition-all duration-1000"
  class:translate-x-20=move|| { !loaded() }
  class:translate-x-0=move|| { loaded() }
>
  hello
</h1>

Solution

  • Yes, there is! You could set a property for content.transform, as per the documentation:

    If you’re authoring content in a format that compiles to HTML (like Markdown), it often makes sense to compile that content to HTML before scanning it for class names.

    Use the content.transform option to transform any content matching a specific file extension before extracting classes:

    Though, you could repurpose it slightly to work for the Leptos files. Tailwind has a default transformer as well as a built-in transformer for Svelte files. This is because Svelte has a similar syntax that would otherwise experience the same problem:

    const builtInTransformers = {
      DEFAULT: (content) => content,
      svelte: (content) => content.replace(/(?:^|\s)class:/g, ' '),
    }
    

    So you could do:

    export default {
      content: {
        transform: {
          rs: (content) => content.replace(/(?:^|\s)class:/g, ' '),
        },
        files: [
          // The `content` array would become `content.files` here.
        ],
      },
    

    Otherwise, you could set a property for the content.extract, keyed by the file extension for the function that extracts the classes:

    export default {
      content: {
        extract: {
          rs: (context) => {
            // …
          },
        },
        files: [
          // The `content` array would become `content.files` here.
        ],
      },
    

    For reference, here is the default extractor in Tailwind. Though this method is undocumented and thus I'd assume not recommended.