tailwind-csstailwind-css-4

How can I pass parameters to a TailwindCSS plugin in a CSS-first configuration?


Starting from TailwindCSS v4, it supports the CSS-first configuration. Based on that, I would like to create a plugin that accepts, for example, a single parameter, true/false. How can I then invoke this plugin in a project and pass the value of this parameter as true/false?

import plugin from 'tailwindcss/plugin'

export const myPluginName = (
  custom: boolean,
) => {
  return plugin(
    ({ addUtilities, theme }) => {
      // ...
    },
  )
}

If I understand correctly, the plugin creation process remains the same. So, in a CSS-first configuration, I should still be able to pass parameters, right?

@import "tailwindcss";

@plugin "myPluginName";

The documentation isn't very verbose when it comes to the search term "plugin".

Use the @plugin directive to load a legacy JavaScript-based plugin:

@plugin "@tailwindcss/typography";

The @plugin directive accepts either a package name or a local path.


Solution

  • @plugin "@tailwindcss/forms" {
      strategy: base;
    }
    

    For example, in the following plugin definition, the options that are passed to the plugin will be the correct types:

    • debug will be the boolean value true
    • threshold will be the number 0.5
    • message will be the string "Hello world"
    • features will be the array ["base", "responsive"]
    @plugin "my-plugin" {
      debug: false;
      threshold: 0.5;
      message: Hello world;
      features: base, responsive;
    }
    

    Example for all types:

    @plugin "my-plugin" {
      is-null: null;
      is-true: true;
      is-false: false;
      is-int: 1234567;
      is-float: 1.35;
      is-sci: 1.35e-5;
      is-str-null: 'null';
      is-str-true: 'true';
      is-str-false: 'false';
      is-str-int: '1234567';
      is-str-float: '1.35';
      is-str-sci: '1.35e-5';
      is-arr: foo, bar;
      is-arr-mixed: null, true, false, 1234567, 1.35, foo, 'bar', 'true';
    }     
    

    We're going to add this to the docs too.

    Specific answer to the question example:

    @import "tailwindcss";
    
    @plugin "myPluginName" {
      custom: true;
    };