为什么在 Tailwind CSS JIT 模式下保存文件时样式不更新,我需要重新启动服务器?

Why styles don't update when saving the files in Tailwind CSS JIT mode and I need to restart the server?

编辑:此问题现已弃用,因为 tailwind 3.0.0 版无需使用 CRACO 即可与 React 一起工作

在 JIT 模式下尝试将 Tailwind 与 React 结合使用时,我添加的 类 没有样式,即使在刷新页面后也是如此。我必须重新启动服务器才能使样式生效。

tailwind.config.js:

module.exports = {
    mode: "jit",
    purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
    ...
}

craco.config.js:

module.exports = {
    style: {
        postcss: {
            plugins: [require("tailwindcss"), require("autoprefixer")]
        }
    }
}

package.json:

{
    "name": "random-name",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@craco/craco": "^6.3.0",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-scripts": "4.0.3",
        "web-vitals": "^1.1.2"
    },
    "scripts": {
        "start": "craco start",
        "build": "craco build",
        "test": "craco test",
        "eject": "react-scripts eject"
    },
    "devDependencies": {
        "@tailwindcss/postcss7-compat": "^2.2.17",
        "autoprefixer": "^9.8.8",
        "postcss": "^7.0.39",
        "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.2.17"
    }
}

package.json中,你应该像

一样在启动脚本上激活监视模式
"scripts": {
   "start": "TAILWIND_MODE=watch craco start",
   ...
}

更新

Tailwind v3.0+ JIT 模式现在是 built-in feature

In Tailwind CSS v3.0, the new engine has gone stable and replaced the classic engine, so every Tailwind project can benefit from these improvements out of the box.


旧答案

这似乎是使用 tailwind JIT 模式时的常见问题,troubleshooting guides 中对此进行了解释。

As of Tailwind CSS v2.2+, the JIT engine depends on PostCSS’s directory dependency messages to register your content files as CSS build dependencies with your build tool. These are a fairly new addition to PostCSS (added in May 2021), and not all build tools have been updated to support them yet.

If your CSS isn’t rebuilding when you change your content files, try setting TAILWIND_MODE=watch as part of your watch script to tell Tailwind to use a legacy dependency tracking strategy instead, which works well with many build tools.

由于 CRACO 用于为 React.js 配置 tailwind CSS,请将其添加到您的 package.json 文件中。

{
  // ...
  scripts: {
    "dev": "TAILWIND_MODE=watch craco start",

    // Do not set TAILWIND_MODE for one-off builds
    "build": "craco build",
    // ...
  },
  // ...
}

此外,请注意

You should only set TAILWIND_MODE=watch when you are actually running a dev server/watch process, and only if your build tool doesn’t yet support PostCSS directory dependency messages. This flag is a temporary workaround for incompatible tooling, and will eventually be removed in a future version of Tailwind CSS.

检查 package.jsonposctcss 版本。当我安装 Tailwind 时它是版本 7,我遇到了同样的问题。我刚刚将 postcss 更新到最新版本,它解决了我的问题。