news

Don’t build! Buy a complete rails SaaS app.

Learn more

Use PurgeCss with Rails (and Tailwind Css)

Sjabloon comes with the amazing TailwindCss, which by default comes with thousands of small utility classes.

For each colour and for each breakpoint there is a small class. All these classes can quickly add up! When working on websites or webapps a never ending goal is to keep it as fast as possible at all times. Keep assets small in size is key in this. That’s why Sjabloon comes with PurgeCss packaged and set up by default.

How it works

PurgeCss works simply by checking for a string within some folders. If the string matches it will keep the Css in place or will remove it otherwise. It’s important to know that it only can detect complete class names, so if you use any conditionals with your classes, be sure to add the class name in its entirety.

How to setup PurgeCss in your Rails app?

First you add PurgeCss to your app using Yarn: yarn add @fullhuman/postcss-purgecss

Next update your PostCss config file (postcss.config.js) in your root as follows:

let environment = {
  plugins: [
    require("tailwindcss")('./tailwindcss.config.js'),
    require("postcss-preset-env")({
    autoprefixer: {
      flexbox: "no-2009"
    },
    stage: 3
    }),
  ]
}

if (process.env.RAILS_ENV === "production") {
  environment.plugins.push(
    require("@fullhuman/postcss-purgecss")({
      content: [
        "./app/views/**/*.html.erb",
        "./app/helpers/**/*rb",
        "./frontend/controllers/**/*.js"
      ],
      defaultExtractor: content => content.match(/[\\w-/:]+(?<!:)/g) || []
    })
  )
}

module.exports = environment

Here first (within “let environment”) your various PostCss plugins are added. In the following section (and only in production if (process.env.RAILS_ENV === "production") {}) PurgeCss is added (push) to the “plugins” array. The PurgeCss plugin accepts a content array where the different paths are added for PurgeCss to check for Css classes (here the views, helpers and stimulus controller folders).

The last line exports the “environment” variable.

If you want to see/check the difference in size between your development and production Css file , run RAILS_ENV=production bin/webpack from the console.

NB. starting with v1.3 Sjabloon uses the PurgeCss settings coming from TailwindCss (see the tailwindcss.config.js file).

A Rails SaaS starter kit to build successful products