【问题标题】:Why is the custom color in tailwind not defined in NextJS production stage为什么NextJS生产阶段没有定义tailwind中的自定义颜色
【发布时间】:2021-09-02 19:55:12
【问题描述】:

我在下一个 js 中为顺风创建了一个自定义颜色。在 localhost 上,定义的颜色看起来很好,但是当我部署到 vercel 时,颜色没有出现。

这是图片本地主机

vercel 制作

tailwind.config.js

const colors = require('tailwindcss/colors');

module.exports = {
  purge: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}'
  ],
  darkMode: false, // or 'media' or 'class'
  theme: {
    colors: {
      transparent: 'transparent',
      current: 'currentColor',
      black: {
        DEFAULT: '#23232D'
      },
      white: colors.white,
      gray: {
        DEFAULT: '#A1A1A1',
      },
      ...
    }
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

ButtonColor/index.js

import PropTypes from 'prop-types';
import { motion } from 'framer-motion';

function ButtonColor({ color, isOpen, onClick }) {

  const variants = {
    open: { width: '100%' },
    closed: { width: '50%' },
  }

  return (
    <motion.div
      className={`bg-${color} h-6 cursor-pointer`}
      onClick={onClick}
      animate={isOpen ? "open" : "closed"}
      variants={variants}
    >
    </motion.div>
  )
}

ButtonColor.propTypes = {
  color: PropTypes.string.isRequired,
  isOpen: PropTypes.bool.isRequired,
  onClick: PropTypes.func.isRequired,
}

export default ButtonColor;

这种情况有什么解决办法吗?谢谢。

【问题讨论】:

  • 最好启用JIT mode,这样您就不会在生产和开发版本之间发现差异(由于 Tailwind)。

标签: next.js tailwind-css


【解决方案1】:

您不能使用 string concatenation 创建 CSS 类名称,因为 PurgeCSS 不会知道在构建过程中保留您的自定义类。

 className={`${color === 'red' ? 'bg-red' : 'bg-blue'} h-6 cursor-pointer`}

或者,您可以在 Next.js 中启用 SCSS 并创建一个 custom global SCSS 文件。在该文件中,使用tailwindcss directives 定义您的样式,同时故意不将您的样式包装在@layer 指令中。不使用@layer 指令告诉tailwind 在构建时不要清除这些类。您需要自己管理这些类的清除。

global.scss

button {
  @apply h-6;
  @apply cursor-pointer;
  &.red{
    @apply bg-red-700 dark:bg-red-900;
    @apply text-white;
    @apply hover:bg-red-800 dark:hover:bg-red-800;
  }
  &.gray {
    @apply bg-gray-300 dark:bg-gray-600;
    @apply text-gray-900 dark:text-gray-200;
    @apply hover:bg-gray-400 dark:hover:bg-gray-500;
  }
}
 <motion.button className={`bg-${color}`}> ...

旁注 - motion.div 应该是 motion.button

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2021-05-25
    • 2021-06-24
    • 2021-11-23
    • 2021-09-02
    • 2022-10-07
    • 2020-06-20
    • 2021-06-01
    • 2021-04-24
    相关资源
    最近更新 更多