rails / cssbundling-rails

Bundle and process CSS in Rails with Tailwind, PostCSS, and Sass via Node.js.
MIT License
579 stars 83 forks source link

Tailwind needs minor changes to allow @imports #24

Closed msmiller closed 2 years ago

msmiller commented 3 years ago

The base installation for using the Tailwind builder works OK until you start trying to @import other CSS. Without imports that can be piped through @apply it's tough to compartmentalize your CSS. To get around this:

  1. Add --postcss to the build:css directive in package.json:
  "scripts": {
    "build:css": "tailwindcss --postcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css"
  }
  1. There's a few node modules that need to be added:
yarn add postcss-import
yarn add postcss-flexbugs-fixes
yarn add postcss
yarn add postcss-preset-env
  1. And then a postcss.config.js needs to be added:
module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-import'),
    require('tailwindcss'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    })
  ]
}
  1. Then put your imports at the start of application.tailwind.css
@import 'home.css';
@import 'foobar.css';

@tailwind base;
@tailwind components;
@tailwind utilities;

Notes: There may be a better way to do this, but this is what I arrived at to get it working. It's a little inconvenient having to manually list imports, but it works. This uses the standard Tailwind PostCSS configs. The Tailwind builder traverses the imports so if you change "foobar.css" it'll trigger a rebuild. The repo I'm working in is using:

gem 'importmap-rails'
gem 'turbo-rails'
gem 'stimulus-rails'
gem 'cssbundling-rails'
dwightwatson commented 3 years ago

It sounds like this is expected of postcss-import as it's adhering the spec strictly.

The Tailwind docs cover this exact issue and provide a solution which basically swaps the @tailwind declarations for @imports.

dhh commented 2 years ago

Documented the this question as part of the FAQ: 2a17da2.