tailwind:如何在 nuxt2 中将 @apply 用于自定义 class?

tailwind: how to use @apply for custom class in nuxt2?

我正尝试在 Nuxt.js 2

中的自定义 class 上使用 @apply

nuxt.config.js

export default {
    buildModules: [
        '@nuxtjs/tailwindcss',
    ],
    tailwindcss: {
        cssPath: '~/assets/app.css',
        exposeConfig: true
    }
}

assets/app.css

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

@layer utilities {
    .btn {
        @apply border-2 p-2 font-bold;
    }
}

在任何 vue 单文件或任何其他 scss 文件中

<style lang="scss">
    .btn-lg {
        @apply btn;
    }
</style>

The btn class does not exist. If you're sure that btn 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

那么,如何让 Tailwind CSS 看到我的自定义样式,然后再处理以使我的自定义 classes 在 @apply 中工作?


我已经尝试了以下问题和文档中的解决方案

但其中 none 有效


我正在使用:

非常感谢您的回复!

正如我在评论中提到的,添加一个mode: "jit"可以解决这个问题。

tailwind.config.js

module.exports = {
    mode: 'jit'
}

这是一个很好的香草解决方案。


但是,如果您像我一样在虚拟机(Homestead)中编写项目,这可能会导致节点无法识别您的 css/scss/sass 文件更改的错误。

所以还有另外两个解决方案:

  1. 使用纯 tailwindcss 而不是 @nuxtjs/tailwindcss

    按照文档:Install Tailwind CSS with Nuxt.js

  2. tailwind.config.css

    中使用 plugin()
    const plugin = require('tailwindcss/plugin')
    const fs = require('fs')
    module.exports = {
      // ... purge, theme, variants, ...
      plugins: [
        plugin(function({ addUtilities, postcss }) {
          const css = fs.readFileSync('./your-custom-style-file-path', 'utf-8')
          addUtilities(postcss.parse(css).nodes)
        }),
     ],
    }
    

    from github

但更重要的是,这个解决方案也无法识别这些变化。所以在 nuxt.config.js 中添加你的 css/scss/sass 文件(我正在使用 nuxt-vite

vite: {
    plugins: [
        {
            name: 'watch-external', // 
            async buildStart(){
                const files = await fg(['assets/**/*']);
                for(let file of files){
                    this.addWatchFile(file);
                }
            }
        }
    ]
}