【问题标题】:Why are css classes are missing in production when using Tailwind and next.js?[NextJs/TailwindCSS]:生产中缺少 css 类
【发布时间】:2020-08-03 03:44:49
【问题描述】:

顺风版:v9.3.5

PostCSS 配置:

// postcss.config.js

module.exports = {
   plugins: {
      tailwindcss: {},
      autoprefixer: {},
      ...(process.env.NODE_ENV === 'production'
         ? {
              '@fullhuman/postcss-purgecss': {
                 content: ['./components/**/*.js', './pages/**/*.js'],
                 defaultExtractor: content =>
                    content.match(/[\w-/:]+(?<!:)/g) || [],
              },
           }
         : {}),
   },
}

顺风配置:

// tailwind.config.js

module.exports = {
   theme: {
      extend: {
         colors: {
            tint: 'rgba(0,0,0,0.3)',
         },
      },
   },
   variants: {},
   plugins: [],
}

样式在开发中完美地工作,但在生产中只有一些样式在工作。检查 build 文件夹中的 CSS 文件后,似乎某些 CSS 类没有被提取或可能被清除,因此导致应用程序的部分样式。

【问题讨论】:

    标签: css reactjs next.js tailwind-css


    【解决方案1】:

    我在同样的问题上苦苦挣扎。 Tailwind will purge classes created with string concatenation.

    一种解决方法是将类名保存为变量。

    n = ‘row-start-2’;
    
    className={n}
    

    对于我的用例,我无法做到这一点。相反,我使用了safelist greedy option

    在顺风配置文件中:

    
    module.exports = {
      purge: {
        content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
        options: {
          safelist: {
            greedy: ["/safe$/"],
          },
        },
      },
    

    然后我将“安全”类添加到我使用字符串连接创建类的所有元素中。

    className={`safe sm:grid-cols-${smCols} sm:grid-rows-${smRows} md:grid-cols-${mdCols} md:grid-rows-${mdRows}
    

    【讨论】:

    • 这个答案是不正确的,起初,这只会将安全类而不是除安全类之外使用的所有类都列入安全名单。其次,您必须对 safelist.greedy 模式使用正则表达式,例如/safe$/ 不带引号。
    【解决方案2】:

    编辑:PurgeCSS 3.0 版添加safelist option,替换白名单

    当我将某些类的名称动态注入到我的 html 模板中时,我遇到了同样的问题。
    我正在使用 nuxt.js/tailwindcss 所以你需要先阅读纪录片来解决你的问题。

    问题

    这是生成生产中缺少的类的代码

     computed: {
        axeY() {
          return this.y < 0 ? `-translate-y${this.y}` + ' ' : `translate-y-1` + ' '
        },
        axeX() {
          return this.x < 0 ? `-translate-x${this.x}` : `translate-x-${this.x}`
        },
    

    PostCSS 会将所有文件分析到 content table(在配置文件中声明),
    注意到我的文件不包含带有 translate 前缀的类
    如您所见,我缺少的课程是:[translate-x-1,-translate-x-1, translate-y-1, -translate-y-1] ...数字 1 是一个变量。

    解决方案

    • 我需要告诉 purgecss 不要通过将这些类添加到白名单中来删除它们
    • 或者您可以在文件中使用它们,例如通过创建一个 unless 文件(由 PostCSS 分析的文件)

    You can specify content that should be analyzed by PurgeCSS with an array of filenames

    • 通过指定您正在使用的所有 cores plugins 来维护 TailWindCSS 的配置文件
    • 在复杂情况下,您可以在配置文件中使用正则表达式。
      就我而言,我可以直接在TailWindCSS 的配置文件中配置purge,通过在options variable 中传递白名单,
      这是我使用第一个解决方案时的配置文件:
    /*
     ** TailwindCSS Configuration File
     **
     ** Docs: https://tailwindcss.com/docs/configuration
     ** Default: https://github.com/tailwindcss/tailwindcss/blob/master/stubs/defaultConfig.stub.js
     */
    const num = [1, 2, 3, 4, 5, 6, 8, 10, 12]
    const whitelist = []
    num.map((x) => {
      whitelist.push('translate-x-' + x)
      whitelist.push('-translate-x-' + x)
      whitelist.push('translate-y-' + x)
      whitelist.push('-translate-y-' + x)
    })
    module.exports = {
      future: {
        removeDeprecatedGapUtilities: true,
      },
      theme: {},
      variants: {
        backgroundColor: ['hover', 'focus', 'active'],
      },
      plugins: [],
      purge: {
        // Learn more on https://tailwindcss.com/docs/controlling-file-size/#removing-unused-css
        enabled: process.env.NODE_ENV === 'production',
        content: [
          'components/**/*.vue',
          'layouts/**/*.vue',
          'pages/**/*.vue',
          'plugins/**/*.js',
          'nuxt.config.js',
        ],
        options: {
          whitelist,
        },
      },
    }
    

    【讨论】:

    • 这个解决方案有效,只是现在不是whitelist而是safelist
    【解决方案3】:

    发现问题,postcss config 缺少内容数组中的部分文件夹,而且由于我的 js 文件有 jsx,我也需要添加它。

    // postcss.config.js
    
    module.exports = {
       plugins: {
          tailwindcss: {},
          autoprefixer: {},
          ...(process.env.NODE_ENV === 'production'
             ? {
                  '@fullhuman/postcss-purgecss': {
                     // added sections folder and changed extension to jsx
                     content: ['./components/**/*.jsx', './pages/**/*.js', './sections/**/**/*.jsx'],
                     defaultExtractor: content =>
                        content.match(/[\w-/:]+(?<!:)/g) || [],
                  },
               }
             : {}),
       },
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 2020-10-17
      • 1970-01-01
      • 2014-07-06
      • 2015-07-12
      • 2021-05-23
      • 2021-10-14
      • 2017-06-02
      • 1970-01-01
      相关资源
      最近更新 更多