Tailwind CSS plugin that lets you write your configuration file with your own custom utilities as though they were native to the framework

  • By J
  • Last update: Aug 8, 2022
  • Comments: 6

🧩 Tailwind CSS Custom Native Utilities

This Tailwind CSS plugin allows you to write configuration for your own custom utility in the theme and variants section of your config as though it were actually part of the framework. Just define it with a single line in the plugins section!

This should allow you to finally kill off leftover CSS and inline styles that have no accompanying plugin-made or native utility. Although you can replace other plugins with this one, it's probably a good idea to use those instead because they're purpose-built and likely to create a better output.

💻 Installation

npm install --save-dev tailwindcss-custom-native

🛠 Basic usage

With this Tailwind configuration,

module.exports = {
  theme: {
    // This utility is not native to Tailwind,
    mixBlendMode: {
      'screen': 'screen',
      'overlay': 'overlay',
    },
    // So we define it here!
    customUtilities: {
      mixBlendMode: {},
      // There are extra parameters for further customization -- see the advanced usage section
    },
  },

  plugins: [
    require('tailwindcss-custom-native'),
  ],
};

this CSS is generated:

.mix-blend-mode-screen {
  mix-blend-mode: screen;
}

.mix-blend-mode-overlay {
  mix-blend-mode: overlay;
}

Variants

When no variants are specified in the variants key of your config, no variants will be generated, as you saw above. (If you would prefer for ['responsive'] to be the default, I am open to changing it).

If you want variants (in the same config as above):

module.exports = {
  theme: {
    mixBlendMode: {
      'screen': 'screen',
      'overlay': 'overlay',
    },
    customUtilities: {
      mixBlendMode: {},
    },
  },

  variants: {
    // All variants, whether added by plugin or not, are at your disposal
    mixBlendMode: ['hover', 'focus'],
  },

  plugins: [
    require('tailwindcss-custom-native'),
  ],
};

you get this additional CSS:

.hover\:mix-blend-mode-screen:hover {
  mix-blend-mode: screen;
}
.hover\:mix-blend-mode-overlay:hover {
  mix-blend-mode: overlay;
}

.focus\:mix-blend-mode-screen:focus {
  mix-blend-mode: screen;
}
.focus\:mix-blend-mode-overlay:focus {
  mix-blend-mode: overlay;
}

⚙️ Full configuration

This plugin expects configuration of the form

theme: {
  customUtilities: {
    key: { property, rename, addUtilitiesOptions },
    // Keep repeating this pattern for more utilities
  },
}

Where each parameter means:

  • key (required, string) - The name of the key for your custom utility, as you wrote in the theme and variants section

  • property (optional, string) - The CSS property that your utility is for

    When not specified, it defaults to kebab-casing (AKA hyphenating) the key. For example, key: 'animationTimingFunction' has corresponding property: 'animation-timing-function').

    This parameter allows you to use a key that may be shorter than the property name, or completely different from it.

  • rename (optional, string) - The prefix before each value name (from theme[key]) in the generated classes

    When not specified, it defaults to kebab-casing (AKA hyphenating) the key. For example, key: 'mixBlendMode' has corresponding rename: 'mix-blend-mode').

    If set to the empty string (''), then there is no prefix and each generated class is just the value name.

  • addUtilitiesOptions (optional, object) - Extra options to pass to the addUtilities function call.

    As of Tailwind 1.2.0, this just means the respectPrefix and respectImportant options

📚 Examples

Specify rename: '' so you can write blur-4 and grayscale instead of filter-blur-4 and filter-grayscale:

module.exports = {
  theme: {
    extend: {
      customUtilities: {
        filter: { rename: "" },
      },

      filter: {
        "grayscale": "grayscale(100%)",
        "blur-4": "blur(1rem)",
      },
    },
  },
  variants: {
    filter: ["responsive"],
  },
  plugins: [
    require("tailwindcss-custom-native"),
  ],
};
.grayscale {
  filter: grayscale(100%);
}

.blur-4 {
  filter: blur(1rem);
}

/* Or whatever screen `sm` is in your config */
@media (min-width: 640px) {
  .sm\:grayscale {
    filter: grayscale(100%);
  }

  .sm\:blur-4 {
    filter: blur(1rem);
  }
}

/* ... and so on for the other screens */

Any property named with a - in front will have that moved to the front of the generated class name, just like the native margin or z-index utilities do.

Let's say you want a section specifically for blur utilities, because they really have nothing to do with other kinds of CSS filters. Use 'blur' as the key and 'filter' as the property:

module.exports = {
  theme: {
    extend: {
      blur: {
        '0': 'blur(0)',
        '1': 'blur(0.25rem)',
        '2': 'blur(0.5rem)',
        // ... as many numbers as you want
      },

      customUtilities: {
        blur: { property: 'filter' },
      },
    },
  },
  variants: {
    blur: ['active'],
  },
  plugins: [
    require('tailwindcss-custom-native'),
  ],
};
.blur-0 {
  filter: blur(0);
}

.blur-1 {
  filter: blur(0.25rem);
}

.blur-2 {
  filter: blur(0.5rem);
}

.active\:blur-0:active {
  filter: blur(0);
}

.active\:blur-1:active {
  filter: blur(0.25rem);
}

.active\:blur-2:active {
  filter: blur(0.5rem);
}

/* and so on for the other numbers you specified */

In practice, you will probably need more than one custom utility, so just add another to the list:

module.exports = {
  theme: {
    customUtilities: {
      listStyleImage: { rename: "list" },
      scrollBehavior: { rename: "scroll" },
    },

    listStyleImage: {
      checkmark: "url('/img/checkmark.png')",
    },

    scrollBehavior: {
      immediately: "auto",
      smoothly: "smooth",
    },
  },
  variants: {},
  plugins: [
    require("tailwindcss-custom-native"),
  ],
};
.list-checkmark {
  list-style-image: url('/img/checkmark.png');
}

.scroll-immediately {
  scroll-behavior: auto;
}

.scroll-smoothly {
  scroll-behavior: smooth;
}

This plugin can piggyback off of other plugins, especially those that register new variants or are missing relevant utilities.

In this case, it is used to add some content utilities that have before and after pseudoselector variants, as provided by tailwindcss-pseudo:

module.exports = {
  theme: {
    extend: {
      content: {
        empty: "''",
        smile: "'\\1F60A'",
        checkmark: "url(/img/checkmark.png)",
      },

      customUtilities: {
        content: {},
      },

      // This is tailwindcss-pseudo config
      pseudo: {
        before: "before",
        after: "after",
      },
    },
  },
  variants: {
    content: ["before", "after"],
  },
  plugins: [
    require("tailwindcss-pseudo")(),
    require("tailwindcss-custom-native"),
  ],
};
.content-empty {
  content: "";
}
.content-smile {
  content: "\1F60A";
}
.content-checkmark {
  content: url(/img/checkmark.png);
}

.before\:content-empty::before {
  content: "";
}
.before\:content-smile::before {
  content: "\1F60A";
}
.before\:content-checkmark::before {
  content: url(/img/checkmark.png);
}

.after\:content-empty::after {
  content: "";
}
.after\:content-smile::after {
  content: "\1F60A";
}
.after\:content-checkmark::after {
  content: url(/img/checkmark.png);
}

😵 Help! I have a question

Create an issue and I'll try to help.

😡 Fix! There is something that needs improvement

Create an issue or pull request and I'll try to fix.

📄 License

MIT


Repository preview image generated with GitHub Social Preview

Github

https://github.com/SirNavith/tailwindcss-custom-native

Comments(6)

  • 1

    > 2.0.0 causes webpack to break

    After updating to any version > 2.0.0, it throws an error in webpack compiling

    ERROR in ./src/css/theme-style.css (./node_modules/css-loader??ref--10-2!./node_modules/postcss-loader/src??postcss0!./src/css/theme-style.css)
    Module build failed (from ./node_modules/postcss-loader/src/index.js):
    SyntaxError
    (5:2) `@apply` cannot be used with `.scroll-behavior-smooth` because `.scroll-behavior-smooth` either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.scroll-behavior-smooth` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.
    

    I reverted to 2.0.0 and all is working again.

  • 2

    [Feature request] Single function call when registering?

    Hey there, thanks for the awesome plugin!

    What do you think about using a single customNative() function call, like so?

    const customNative = require('tailwindcss-custom-native');
    
    module.exports = {
      // ...
      
      plugins: [
        customNative([
          { key, property, rename },
          { key, property, rename },
          // ...
        ]),
      ]
    }
    
  • 3

    chore(deps): bump minimist from 1.2.0 to 1.2.5

    Bumps minimist from 1.2.0 to 1.2.5.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

  • 4

    feat: configure multiple custom utilities in a single function call

    The customNative function is now variadic, so it can accept multiple configurations, meaning that what used to be written as:

    plugins: [customNative(config1), customNative(config2), customNative(config3)]
    

    can now be written as:

    plugins: [customNative(config1, config2, config3)]
    

    The documentation has been updated to reflect this.

    This closes #2

  • 5

    Bump lodash from 4.17.11 to 4.17.13

    Bumps lodash from 4.17.11 to 4.17.13.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot ignore this [patch|minor|major] version will close this PR and stop Dependabot creating any more for this minor/major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

  • 6

    JIT customization

    What an awesome plugin! I've been searching for something just like this. Does Tailwind CSS Custom Native Utilities also support making customizations to the JIT compilation process?

    I've been curious for a while about creating dynamic features that combine multiple properties. For example:

    shadow-green-300
    

    …would combine the shadow color and tint amount in one single property name.

    If that's possible, my next thought would be to support pulling those values in dynamically from other set properties. For example:

    shadow-background-300
    

    …would pull the shadow color from the set background color. Under the hood, I imagine this might work similarly to the JIT compiler's new bracket notation for static values, though I'll refrain from going down that rabbit hole.