rails / cssbundling-rails

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

Bundling does not work with dynamic styles in helpers #57

Closed arielscherman closed 2 years ago

arielscherman commented 2 years ago

What

I have created a fresh rails 7 app, with tailwind. Without changing any config at all, I started building the app, and running the server/foreman with ./bin/dev. However, for some reason, some styles used in helpers are not properly bundled. Therefore those are not working when rendering the page (as they are not included in the final CSS)

Why

If you use tailwind CSS classes in rails helpers, they will be bundled unless they are dynamically generated.

If you do this:

# /helpers/application_helper.rb
def some_helper
  content_tag :span, "Foo", class: "bg-green-100"
end

It works fine, but if you render the styles by embedding a variable:

# /helpers/application_helper.rb
def some_helper
  color = "green"
  content_tag :span, "Foo", class: "bg-#{color}-100"
end

It doesn't work, and bg-green-100 is not included in the bundled styles.

Same thing happens with svgs. They are properly loaded if you pasted them in the HTML, but once you use a rails helper to embed it, they are not bundled anymore.

For svg's, I could fix it by adding the folder with the svgs to the tailwind.config.js file:

content: [
    './app/assets/images/svgs/**/*.svg'
]

But I am not sure what to do with tailwind css classes used in helpers. What is the best thing to do here?

eelcoj commented 2 years ago

You shouldn't construct class names but use complete classnames. Check out the TailwindCss docs for more.