Serving CSS via Webpack

Learn to style our apps with CSS via Webpack.

Overview of CSS stylesheets

We’ve been writing CSS in files located in app/assets/stylesheets. Rails will find whatever .css files are there, bundle them all up together, and make the combined CSS available to your views. If we want to use modern CSS tools or techniques, such as CSS modules or Post CSS, it’s not possible to do so with the default configuration Rails provides.

The part of Rails that handles CSS is called Sprockets, and while new gems are always being produced to give Sprockets new abilities, the state of the art in CSS is part of the JavaScript ecosystem and available via Webpack. In earlier versions of Rails, setting up Webpack was extremely difficult. However, as we learned in Entering Additional Payment Details, Rails now includes full support for Webpack, and it turns out that Webpacker has configured Webpack to serve CSS already!

Modifying the app with Webpack

We’ll modify the app so that Webpack is serving CSS. We’ll demonstrate the benefit of this by installing cssnext, which allows us to use features of CSS that aren’t supported in the browser by post-processing the CSS we write.

Webpacker configured Webpack to look for CSS in app/javascript/packs, which is strange. Since it’s the default, let’s go with it though. Move app/assets/stylesheets/application.scss into app/javascript/packs. Next, create the directory app/javascript/packs/css, and move all the other .scss files from app/assets/javascripts into that directory.

If we open up app/javascript/packs/application.scss, we should see a large comment at the top of the file. At the end of the comment, there are two directives that look like this:

These directives tell Sprockets to include all the .scss files in the current directory, which allows us to put CSS in several different files. Webpack doesn’t support these directives, so we’ll need to add some code to application.scss to replicate what they do.

As mentioned way back in Making Prettier Listings, our CSS files are actually Sass files, and Sass has the ability to import external files using @import. Unfortunately, we can’t @import all files with one line of code, so we’ll need to add one @import for each file:

Get hands-on with 1200+ tech skills courses.