Create classes which extend Tailwind css classes

Viewed 6329

I use Tailwind for my project and I would like to create classes which use tailwind existing classes. For example, my buttons currently look like this:

<button class="text-light-blue bg-white rounded-full border-solid border-2 border-light-blue py-1 px-4 box-border shadow hover:bg-blue-700 hover:text-white hover:border-blue-700">
       Button
</button>

As you can see I use a lot of classes and I would like to have instead something like this:

<button class="app-btn"> Button </button>

with

@import '/node_modules/tailwindcss/utilities.css';

.app-btn { 
   @extend .text-light-blue;
   @extend .bg-white;
   ...
}

but when I try to do this I have the following error:

SassError: ".app-btn" failed to @extend ".bg-white".
       The selector ".bg-white" was not found.
       Use "@extend .bg-white !optional" if the extend should be able to fail.
        on line 4 of src/assets/styles/app-shared-style.scss

Is there a way to achieve what I'm trying to do? Thanks

4 Answers

I found the solution: You need to install postcss-import with npm install postcss-import, tweek the postcss.config.js with:

module.exports = {
  plugins: [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
  ]
}

and then you can create classes based on the lib classes with:

@import 'tailwindcss/utilities';
@import 'tailwindcss/base';
@import 'tailwindcss/components';

.app-btn {      
  @apply text-white;
  @apply rounded-full;
  @apply py-1;
  @apply px-4;
  @apply shadow;
  &:hover {
    @apply bg-blue-700;
  }
}

You can just do this:

.app-btn {
@apply text-white rounded-full py-1 px-4 shadow hover:bg-blue-700.
}

if you use laravel mix

const mix = require('laravel-mix');

You need to configure your webpack.mix.js in one of the following ways

1] you can either use postCss like this

mix.postCss('resources/css/app.css', 'public/css', [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
]);

2] or, you can use sass like this

mix.sass("resources/css/app.scss", "public/css").options({
    postCss: [
        require('postcss-import'),
        require('tailwindcss'),
        require('autoprefixer'),
    ], });

Example:

    .input {
        @apply p-2 text-center mb-2 border rounded focus:outline outline-2 focus:outline-blue-500;
    }

    .file-input {
      @apply input border-none text-slate-500 leading-10 file:block md:file:inline-block file:w-full md:file:w-auto file:btn file:h-min file:border-none file:cursor-pointer file:mx-3;
    }

No CSS preprocessor needed

Related