Build a PostCSS pipeline

Written by
Juan Gallardo
Published
Last updated

Table of Contents

Our goal is to build CSS that is themable, re-usable, and efficient

Organization

We are using PostCSS, which we set up via a flag in our rails new command. You can refer to article 1 in this series. rails new --css=postcss

Instead of using a bunch of @requires url(<RELATIVE_PATH_TO_CSS_FILE>); statements. Let’s inline all the styles in our /app/assets/stylesheets/ folder automatically. Let’s also import any CSS under /app/views so we can keep our component styles next to their ruby source files

1
2
3
4
5
6
7
8
9
/* /app/assets/stylesheets/application.postcss.css */

/* Entry point for your PostCSS build */

/* Import all stylesheets in the stylesheets folder */
@import-glob "./**/*.css";

/* Import all component styles */
@import-glob "../../views/**/*.css";

To make this work, we need to install the postcss-import-ext-glob postcss plugin. Make sure to place it before postcss-import in your pipeline

yarn add postcss-import-ext-glob

1
2
3
4
5
6
7
8
9
10
// /postcss.config.js

module.exports = {
  plugins: [
    require('postcss-import-ext-glob'),
    require('postcss-import'),
    require('postcss-nesting'),
    require('autoprefixer'),
  ],
}

Now we don’t have to modify our postcss entrypoint ever again. Every time we write more CSS code we’ll create a new file and place it wherever it belongs in our folder structure

.
└── app/
    ├── assets/
    │   └── stylesheets/
    │       ├── global/
    │       │   └── reset.css
    │       ├── components/
    │       │   ├── prose.css
    │       │   ├── link.css
    │       │   ├── button.css
    │       │   └── etc.css
    │       └── application.postcss.css
    └── views/
        └── components/
            └── navbar/
                ├── navbar.css
                └── navbar.rb

Like this diagram? You can make your own! tree.nathanfriend.com Everything will be piped into one file. Our aim is to write modular code and keep specificity as low as possible