Table of contents
1.
Introduction🧐
2.
Installation💻
3.
CSS Bundling tooling options🧠
3.1.
Bulma 
3.2.
Bootstrap 
3.3.
PostCSS 
3.4.
Dart Sass
3.5.
Tailwind CSS 
4.
How To Add Bootstrap to a Ruby on Rails Application
4.1.
Save and close the file when you are finished editing.
5.
CSS Bundling in Ruby on Rails💯 
5.1.
Installers
5.2.
Build Watcher
5.3.
Detection of changes in stylesheet
5.4.
Deployment of application
5.5.
Testing
6.
Why use CSS Bundling in Ruby on Rails? 🤔
7.
Frequently Asked Questions
7.1.
What is CSS explained?
7.2.
What is Bootstrap? 
7.3.
What is Tailwind CSS?
7.4.
How can I use Tailwind to import relative CSS files?
7.5.
Why do we get application.css not in the asset pipeline in production?
8.
Conclusion
Last Updated: Mar 27, 2024

CSS Bundling in Ruby on Rails

Author ANJU JAISWAL
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction🧐

Hi Ninja🥷! Grab your coffee, and let's cover an exciting topic, CSS Bundling in Ruby on Rails. Do you know when part of the Rails 7 release came to an optional gem called CSS bundling rails.                                                   

CSS Bundling in Ruby on Rails

 

This offers installers for the most popular CSS tools. We'll learn how to use this gem to improve the CSS we can use and create in this article. We won't go into detail about each tool because how you use them will depend on your needs, but we will discuss why you might use each one.

Installation💻

Installing a new Rails 7 app is as easy as adding a command line argument when the app is created.

rails new myapp --css [tailwind|bootstrap|bulma|postcss|sass]

 

So if you wanted to use Bootstrap, you'd run

rails new myapp --css bootstrap

 

To use an already-existing application, take the following actions.

  • 'cssbundling-rails ' added to Gemfile
  • Run the command line program bundle install.
  • You can install the necessary tooling using the generator offered by the gem by typing ./bin/rails css:install:[tailwind|bootstrap|bulma|postcss|sass]. To install Bootstrap, for example, you would type./bin/rails CSS:install:bootstrap.

CSS Bundling tooling options🧠

CSS Bundling in Ruby on Rails offers installation support for five different CSS processing and bundling tools.

Bulma 

A Bootstrap substitute. Has partisan styling to get you up and running if you lack the CSS expertise to create your websites.

Bootstrap 

When you need a proof of concept, this is likely one of the most well-known libraries to start with the look and feel of a new application.                               

Bootstrap

PostCSS 

A Javascript tool for CSS transformation. Thanks to this, you can use future CSS features that aren't supported by all browsers or one of the many postcss plugins to improve your CSS.

Dart Sass

The hottest style of sass file processing right now. It is a way to expand your capabilities by adding more CSS features.

Tailwind CSS 

A CSS framework with a focus on utility. You add CSS to your application by adding classes to your HTML; it functions similarly to Bootstrap. Where Tailwind differs is that you can build up your design using reusable classes that only perform one function rather than using it as a way to avoid understanding CSS. Instead of being placed under a class name in your CSS files, it moves the CSS to the markup. Either you'll adore it, or you won't.            

Tailwind css

How To Add Bootstrap to a Ruby on Rails Application

This step involves including Bootstrap and the tool libraries it needs to operate properly in your project. In order to do this, libraries and plugins must be imported into the webpack entry point and environment files for the application. Additionally, you'll need to create a unique style sheet in the app/javascript directory of your application, which is where the project's JavaScript assets are stored.

Install Bootstrap and its necessary dependencies first using yarn:

yarn add bootstrap jquery popper.js
You can also try this code with Online Ruby Compiler
Run Code

This command will make sure that you have the libraries you need because a lot of Bootstrap's components need Popper.js, JQuery, and Bootstrap's own custom plugins.

Next, open config/webpack/environment.js, the main webpack configuration file, in nano or your preferred editor:

nano config/webpack/environment.js
You can also try this code with Online Ruby Compiler
Run Code

Include the webpack library and a ProvidePlugin that instructs Bootstrap how to interpret JQuery and Popper variables inside the file.

the file with the following code:

~/rails-bootstrap/config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const webpack = require("webpack") 

environment.plugins.append("Provide", new webpack.ProvidePlugin({ 
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}))  

module.exports = environment

You can also try this code with Online Ruby Compiler
Run Code

When using JQuery or Popper modules, we can avoid using multiple import or require statements by using the ProvidePlugin. When using this plugin, Webpack will automatically load the appropriate modules and point named variables to the loaded exports of each module.

When you're done editing, save and close the document.

Next, open app/javascript/packs/application.js, your primary webpack entry point file:

nano app/javascript/packs/application.js
You can also try this code with Online Ruby Compiler
Run Code

In the file, include the import statements listed below to bring in Bootstrap and the custom.scss styles file you will be creating afterward:

. . . 
[label ~/rails-bootstrap/app/javascript/packs/application.js]
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

import "bootstrap"
import "../stylesheets/application"
. . . 
You can also try this code with Online Ruby Compiler
Run Code

Save and close the file when you are finished editing.

Next, make a directory for stylesheets for your application style sheet:

mkdir app/javascript/stylesheets
You can also try this code with Online Ruby Compiler
Run Code

Open the custom styles file:

nano app/javascript/stylesheets/application.scss
You can also try this code with Online Ruby Compiler
Run Code

In this scss file, Sass is used in place of CSS. Syntactically Awesome Style Sheets (Sass), a CSS extension language, enables programmers to incorporate shared variables and other programming conventions into styling rules.

Add the following lines to the file to import the project's customised Bootstrap scss styles and Google fonts:

~/rails-bootstrap/app/javascript/stylesheets/application.scss

@import "~bootstrap/scss/bootstrap";
@import url('https://fonts.googleapis.com/css?family=Merriweather:400,700');
You can also try this code with Online Ruby Compiler
Run Code

Add next the application's unique variable definitions and styles:

~/rails-bootstrap/app/javascript/stylesheets/application.scss

. . .
$white: white;
$black: black;

.navbar {
        margin-bottom: 0;
        background: $black;
}
body {
        background: $black;
        color: $white;
        font-family: 'Merriweather', sans-serif;
}
h1,
h2 {
        font-weight: bold;
}
 . . .
You can also try this code with Online Ruby Compiler
Run Code

When you're done editing, save and close the document.

Your project now includes Bootstrap as well as some unique styles. The next step is to incorporate Bootstrap layout guidelines and elements into your application files

CSS Bundling in Ruby on Rails💯 

Installers

With the help of this gem, you can quickly start using the bundler of your choice in a new Rails application. It also outlines how to use the app/assets/builds convention to store your bundled output as artefacts outside of source control (the installer adds this directory to .gitignore by default).

Build Watcher

When using this method, you run the bundler in watch mode in a terminal by typing yarn build: CSS —watch (and, if you're not using something like puma-dev, your Rails server in another). If you're using jsbundling-rails, you can start a JS build watcher in addition to the CSS build watcher by using the command./bin/dev.

Detection of changes in stylesheet

The bundler will app/assets/stylesheets/application.[bundler].css  each time it notices changes to any of the stylesheet files in your project, into app/assets/builds/application.css. This build output replaces the default asset pipeline file. So you keep using the common asset pipeline approach to refer to the build output in your layout with % = stylesheet link_tag "application" %>.

Deployment of application

The css: build task is attached to the assets: precompile task when you deploy your application to production to ensure that all of your package.json dependencies are met. The yarn build:css command processes your stylesheet entry point as it would in development after JSON has been installed. The asset pipeline takes this output, digests it, and copies it like any other asset pipeline file into public/assets.

Testing

The bundler attaches to the test:prepare test tasks to ensure the stylesheets have been bundled before testing begins. (Take note that "rails test" does not load test: prepare; this only applies to rails test:* tasks, such as test:all or test: controllers.)

In the absence of a test: prepare a definition in your test framework. Before testing begins, ensure that your test framework executes the rake task css: build to bundle stylesheets. You must also run javascript:build if your setup uses jsbundling-rails (e.g., esbuild + Tailwind).

Why use CSS Bundling in Ruby on Rails? 🤔

  • There are other ways to incorporate tools like Bulma into your application besides using the CSS Bundling in the Ruby on Rails gem. For those libraries, there are gems, and npm packages or you can even reference the directly hosted minified files through a CDN.
  • The README of the cssbundling-rails gem also makes a note of the existence of gems for Tailwind and dartsass that can be integrated into your application without the need for node.js installation.
  • However, the CSS Bundling in Ruby on Rails gem enables us to quickly and easily install those tools and get them up and running in a Rails application. With this help, build times can be decreased because you can develop much more quickly without importing the entire library.
  • This would be the first gem you look for if you want something different from the default Rails method of creating stylesheets mapped to controller names.
    Check this out:  Versions of CSS

Frequently Asked Questions

What is CSS explained?

CSS is a stylesheet language used to describe how a document written in HTML or XML is presented. CSS specifies how elements should be displayed in various media, including speech, paper, and the screen.

What is Bootstrap? 

A robust front-end framework called Bootstrap is used to build contemporary websites and web apps. Numerous HTML and CSS templates are provided for UI interface elements like buttons and forms, yet it is open-source and free to use. JavaScript extensions are supported by Bootstrap as well.

What is Tailwind CSS?

An efficient CSS framework for creating unique user interfaces is called Tailwind CSS. Its low-level CSS framework is highly customizable and provides all the building blocks required to create custom designs without requiring you to struggle to override obnoxious, opinionated styles.

How can I use Tailwind to import relative CSS files?

You must set up Tailwind to use postcss and postcss-import if you want to include @import statements in your application.js file. Instead of combining all your CSS files into one huge file, you should also consider directly referencing your other CSS files.

Why do we get application.css not in the asset pipeline in production?

The common problem is that your repository does not have the output directory required by the build commands. The presence of an app/assets/builds would be beneficial. By adding the directory that contains the a.gitkeep file, you can guarantee that it is accessible in production.

Conclusion

In this post, you learned a brief overview of CSS Bundling in Ruby on Rails, its installation is pretty straightforward, and we know why it is used.

Here are a few key websites that will aid in your exploration of Ruby on Rails.

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning, and many more! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc.; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!                                

Thank you
Live masterclass