Get Up and Running with PostCSS using PostCSS CLI

Last reviewed on December 24, 2020

In this post, I cover how to get up and running with PostCSS using PostCSS CLI and go over popular plugins including postcss-import, autoprefixer, and cssnano.

First, install postcss and postcss-cli:

Terminal
npm i -D postcss postcss-cli

We can run PostCSS from the command line as follows:

Terminal
./node_modules/.bin/postcss --help

Now let's say I have the following project structure:

/css
  main.css
  base.css
  autocomplete.css

These CSS files contain the following code:

main.css
@import './base.css';
@import './autocomplete.css';
base.css
html {
  color: blue;
}

select {
  appearance: none;
}
autocomplete.css
.autocomplete {
  color: #777;
}

Let's add a command to the scripts block of our package.json to process our CSS using PostCSS:

{
  "scripts": {
    "postcss:watch": "postcss css/main.css --dir dist --watch"
  }
}

If we run npm run postcss:watch, we'll see css/main.js copied into a dist folder. Nothing useful happened at this point. Let's add some PostCSS plugins to make things more interesting.

Terminal
npm i -D postcss-import autoprefixer cssnano

postcss-import

The postcss-import plugin will replace the @import statements in main.css with the actual code of those files.

autoprefixer

The autoprefixer plugin will add vendor prefixes to CSS rules using values from Can I Use.

cssnano

The cssnano plugin will optimize our CSS to ensure that the final result is as small as possible for a production environment.

Using PostCSS Plugins

To use these plugins, create the file postcss.config.js in the root of your project and import each plugin in the plugins array as follows:

postcss.config.js
module.exports = {
  plugins: [
    require('postcss-import'),
    require('autoprefixer'),
    require('cssnano')({
      preset: 'default',
    }),
  ],
};

Now if we run npm run watch:postcss, we'll see all of our CSS minified in dist/main.css with vendor prefixes.

The code for this post can be found on GitHub.