创建扩展 Tailwind css 类的类

Tim*_*age 3 css sass tailwind-css

我在我的项目中使用 Tailwind,我想创建使用 Tailwind 现有类的类。例如,我的按钮目前看起来像这样:

<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>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我使用了很多类,我想要这样的东西:

<button class="app-btn"> Button </button>
Run Code Online (Sandbox Code Playgroud)

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

.app-btn { 
   @extend .text-light-blue;
   @extend .bg-white;
   ...
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这样做时,出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

有没有办法实现我想要做的事情?谢谢

Kay*_*ote 14

你可以这样做:

.app-btn {
@apply text-white rounded-full py-1 px-4 shadow hover:bg-blue-700.
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*age 5

我找到了解决方案:您需要postcss-import使用npm install postcss-import, tweek安装postcss.config.js :

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

然后你可以创建基于 lib 类的类:

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为使用单个“@apply”并将每个道具列出在自己的行上要干净得多,即:``@applyrelative max-w-3xl mx-auto; ```` (2认同)