JIT tailwindcss 在 bg-[] 中使用变量不渲染颜色

Max*_*lle 17 next.js tailwind-css

当像这样传递我的颜色作为道具时<List text="something" color="#84AB86" /> and using in the code className={'bg-[${color}] '} it does not render properly.

当查看 chrome 开发工具时,颜色已正确添加,如下所示bg-[#84AB86]

当手动放置颜色而不从道具中取出颜色时,它确实可以正常工作

经过更多测试后,似乎也不可能这样做

const color = "#84CC79"
className={`bg-[${color}]`}
Run Code Online (Sandbox Code Playgroud)

知道为什么吗

Dan*_*ila 11

要将动态类与 JIT Tailwind 一起使用,您需要使用safelist配置键或创建存根文件,在其中列出您将使用的所有动态类。

配置示例:

module.exports = {
  content: [
    './pages/**/*.{html,js}',
    './components/**/*.{html,js}',
  ],
  safelist: [
    'bg-red-500',
    'text-3xl',
    'lg:text-4xl',
  ]
  // ...
}
Run Code Online (Sandbox Code Playgroud)

safelist.txt或者在你的文件夹中创建src,然后在其中添加类,如下所示:

bg-[#84AB86]
bg-[#fffeee]

// etc..
Run Code Online (Sandbox Code Playgroud)

并且不要忘记将此safelist.txt文件包含到您的配置中content,以便 Tailwind 可以观看它。

Tailwind 文档的解释

如果您不使用 JIT,那么您可以使用safelistPurgeCSS 选项:

// tailwind.config.js
module.exports = {
  purge: {
    // Configure as you need
    content: ['./src/**/*.html'],
    // These options are passed through directly to PurgeCSS
    options: {
      // List your classes here, or you can even use RegExp
      safelist: ['bg-red-500', 'px-4', /^text-/],
      blocklist: [/^debug-/],
      keyframes: true,
      fontFace: true,
    },
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)