Tailwind CSS 样式未在部署时应用

Mar*_*ark 5 css deployment github-pages tailwind-css

这是我第一次使用 Tailwind CSS 来设计我的 React 应用程序。当我在本地运行应用程序时,它的样式非常完美,但是,既然我已经使用它进行了部署gh-pages,则无需应用任何样式。我需要更改我的 package.json 文件或其他内容吗?

链接到实时站点

{
  "name": "seafaring",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://superhackerboy.github.io/sweet-seafaring-dreams/",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "gh-pages": "^2.2.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "build:css": "postcss src/styles/tailwind.css -o src/styles/index.css",
    "watch:css": "postcss src/styles/tailwind.css -o src/styles/index.css --watch",
    "start": "cross-env NODE_ENV=development concurrently \"npm run watch:css\" \"react-scripts start\"",
    "build": "cross-env NODE_ENV=production concurrently \"npm run build:css\" \"react-scripts build\"",
    "test": "react-scripts test",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@fullhuman/postcss-purgecss": "^2.1.0",
    "autoprefixer": "^9.7.4",
    "concurrently": "^5.1.0",
    "cross-env": "^7.0.0",
    "cssnano": "^4.1.10",
    "postcss-cli": "^7.1.0",
    "purgecss": "^2.1.0",
    "tailwindcss": "^1.2.0"
  }
}

Run Code Online (Sandbox Code Playgroud)

小智 7

我有类似的问题。

就我而言,我使用动态设置的颜色类,例如 className= text-${color}-500

这就是问题所在。

如果您按照官方 Tailwind 文档设置所有内容,您也会自动设置 purgeCSS。然后,这将在构建过程中从 tailwind 文件中删除所有未使用的 CSS 类(在部署到 gh-pages 的示例中)

要解决这个问题,您必须在某处具体写下类名,因为purgeCSS 会查找与项目中现有类名匹配的任何字符串

就我而言,我只是在我的一个文件中使用了这样的多行注释:

  /**
   * PurgeCSS:
   * text-red-500
   * text-green-500
   * text-yellow-500
   * text-gray-500
   * text-purple-500
   * text-indigo-500
   * text-blue-500
   * text-pink-500
   *

   */
Run Code Online (Sandbox Code Playgroud)

这解决了 tailwind / purgecss 的任何构建问题,我现在可以愉快地在我的项目中使用动态类。

希望这有帮助,我知道有点晚了,但我只是在尝试自己解决这个问题时偶然发现了这个问题!


小智 7

虽然目前 Fred 的最佳答案是一个可行的解决方案。我在 Tailwind 文档中找到了更好的解决方案。

您可以在 tailwind.config.js 中指定一个安全列表,此安全列表中指定的类永远不会被清除。

// tailwind.config.js
module.exports = {
  purge: {
    content: ['./src/**/*.html'],
    safelist: [
      'bg-blue-500',
      'text-center',
      'hover:opacity-100',
      // ...
      'lg:text-right',
    ]
  },
  // ...
}
Run Code Online (Sandbox Code Playgroud)

更多信息:https://tailwindcss.com/docs/optimizing-for-production#safelisting-specific-classes