weapp-tailwindcss icon indicating copy to clipboard operation
weapp-tailwindcss copied to clipboard

@layer中自定义的类偶尔会失效

Open MoeHero opened this issue 6 months ago • 8 comments

描述这个Bug 偶尔会出现报错如下 [plugin:vite:css] [postcss] path/to/src/Component.vue?vue&type=style&index=0&scoped=68ebadeb&lang.scss:39:3: The center class does not exist. If center is a custom class, make sure it is defined within a @layer directive.

重新编译几次之后又会正常

如何重现

运行环境

  • OS: Windows11
  • Nodejs: 20
  • Framework: uni-app

MoeHero avatar Jan 09 '24 08:01 MoeHero

看上去这是一个uni app vue3 vite项目,请问这个 center 这个类是如何定义的呢?定义在插件里面,还是定义在普通的 css 里面。

最好能提供一个能复现的 demo,不然这种偶发性问题还是挺难排查的。

sonofmagic avatar Jan 09 '24 10:01 sonofmagic

src/styles/index.scss 里,相关片段如下

@layer utilities {
  .center {
    @apply flex justify-center items-center;
  }
}

这个文件在 App.vue 里引用的,相关片段如下

<style lang="scss">
@import './styles/index.scss';

@tailwind base;
@tailwind components;
@tailwind utilities;
</style>

至于能复现的 demo 我没写过,而且不知道拿出去的话会不会出问题,现在是公司的项目里报错,而且多重新编译几次就好了 之前一直没处理这个事情,现在想上 ci,如果因为这个问题导致编译失败就有点难搞

MoeHero avatar Jan 09 '24 12:01 MoeHero

我试了一下,暂时没复现,猜想不知道会不会和这个有关系: https://tailwindcss.com/docs/using-with-preprocessors#build-time-imports

image

我看教程里的 @layer 都是定义在:

@tailwind base;
@tailwind components;
@tailwind utilities;

下方的

https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes

sonofmagic avatar Jan 09 '24 14:01 sonofmagic

我发现直接在 App.vue 里写 @layer utilities 好像一直是正常的,但 import 的就会有问题 而且好像只有 center 这个类有问题,其他的类好像都是正常的没报错,很奇怪

Update: 刚刚又跑了一次,直接写在 App.vue 里也会报错

MoeHero avatar Jan 09 '24 16:01 MoeHero

那我推荐你注册这样一个 tailwindcss/plugin

// tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function ({ addUtilities }) {
      addUtilities({
        '.center': {
          display: 'flex',
          'align-items': 'center',
          'justify-content': 'center'
        }
      })
    })
  ]
}

这样做,性能比 @apply 要好,同时vscode插件能感知到这个 class 来产生智能提示,可能还能规避你这个报错问题。

sonofmagic avatar Jan 11 '24 02:01 sonofmagic

改完之后 cneter 不报错了,然后 @layer utilities 的另一个类又报错了...

MoeHero avatar Jan 11 '24 20:01 MoeHero

有可以稳定复现的 repo 吗,或者都写到插件里,不用 @layer utilities 呢,哈哈

sonofmagic avatar Jan 12 '24 15:01 sonofmagic

我晚点忙完试试看能不能分离出来一个 demo 试试看,现在有点忙,而且项目是公司的不太方便公开

MoeHero avatar Jan 12 '24 15:01 MoeHero

长期没有回复,先 Close 了,有复现或者还是遇到这个问题再 reopen 吧

sonofmagic avatar Apr 01 '24 11:04 sonofmagic