Rails 6中Tailwind CSS安装后样式不生效问题求助
Let's break down the likely issues causing your Tailwind styles not to load, based on the config files you shared:
1. Webpacker & Webpack Version Mismatch
Your package.json shows @rails/webpacker: 3.5, but Webpack 4 requires Webpacker 4.x or higher (Webpacker 3.x is built for Webpack 3). This version conflict can break the compilation pipeline, preventing your styles from being processed correctly.
Fix:
Upgrade Webpacker to a version compatible with Webpack 4:
yarn upgrade @rails/webpacker@4.3.0
Double-check that your Webpack version aligns with Webpacker 4.x (it should be Webpack 4.x).
2. Mismatched File Paths in Your Import
In packs/application.js, you're requiring stylesheets/application.scss, but your actual Tailwind entry file lives at javascript/css/application.css. Webpack can't find the correct file to process, so your Tailwind styles never make it into the bundle.
Fix:
Either adjust the import path to point to your actual CSS file:
// packs/application.js require("../css/application.css")
Or move your Tailwind entry file to app/javascript/stylesheets/application.css (this follows Webpacker's standard directory structure for styles).
3. Incorrect PostCSS Plugin Order
PostCSS runs plugins in the order they're listed, and postcss-import needs to come first to properly resolve @import statements. In your postcss.config.js, you have tailwindcss before postcss-import, which means Tailwind's @import rules won't be parsed correctly.
Fix:
Reorder your plugins so postcss-import is first:
// postcss.config.js module.exports = { plugins: [ require('postcss-import'), require('tailwindcss'), require('autoprefixer'), require('postcss-flexbugs-fixes'), require('postcss-preset-env')({ autoprefixer: { flexbox: 'no-2009' }, stage: 3 }) ] }
4. Incorrect Stylesheet Pack Tag Reference
In application.html.erb, you're using stylesheet_pack_tag 'stylesheets', but if your styles are imported through packs/application.js, Webpack will bundle them into the application pack's CSS file. Unless you have a separate packs/stylesheets.js entry point, this tag is pointing to a non-existent file.
Fix:
Remove the stylesheet_pack_tag 'stylesheets' line, and keep only the tag for your main application pack:
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
This will load the CSS bundled alongside your application.js file.
5. Stale Asset Cache
Sometimes old cached assets can prevent new styles from loading. Clear your asset cache and recompile:
Fix:
rails assets:clobber yarn build:webpack
After addressing these points, restart your Rails server and Webpack dev server, then check if your Tailwind styles are applied correctly.
内容的提问来源于stack exchange,提问作者Steven Aguilar

