Rails 7 added --css app generator

Modern web applications are more likely than not to use a CSS framework like Tailwind, Bootstrap, or Bulma. In Rails, asset pipeline adds the ability to write CSS and Javascript assets in other languages and pre-processors such as CoffeeScript, Sass, and ERB. It allows assets in the Rails application to be automatically combined with assets from other gems.

Rails automatically adds the sass-rails gem to our Gemfile, which is used by Sprockets for Sass compilation. But Sass has chosen to focus exclusively on dart-sass, which requires all manner of dependencies that Rails won’t adopt by default. To decrease our reliance on Sass, Rails 7 removed default reliance on Sass and CSS generators and this comes with the idea of using a generator for configuring the CSS processor.

Before

To create a new Rails application, all one has to do is:

rails new myapp

This command creates the Rails application and uses Sass as their default CSS processor. If we had to use another CSS processor, we would need to configure it manually after creating the application.

After

With Rails 7, we now can create a new Rails application and configure it with the CSS processor options. Add –css app generator option PR added the --css option to the Rails app generator. Currently, this generator supports the options bootstrap, bulma, sass, and postcss.

rails new myapp --css tailwind

When we pass tailwind, it’ll use tailwindcss-rails gem on an importmap/no-JS setup, otherwise cssbundling-rails gem.

After building a Rails 7 application with the above command, the app/views/layout/application.html.erb looks like,

<!DOCTYPE html>
<html>
  <head>
    <title>Rails7AppTest</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag "inter-font", "data-turbo-track": "reload" %>
    <%= stylesheet_link_tag "tailwind", "data-turbo-track": "reload" %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <main class="container mx-auto mt-28 px-5 flex">
      <%= yield %>
    </main>
  </body>
</html>

This will automatically link the tailwind styles to the application.

Need help on your Ruby on Rails or React project?

Join Our Newsletter