PostCSS
Do you want to use future CSS features in your code right now? Want to never have to worry about those pesky vendor prefixes ever again? PostCSS is the answer!
In this simple, easy to understand article I will guide you through setting up and using PostCSS in your projects.
Requirements
The only thing you need is the latest version of Node.js.
Getting Started
First, navigate to your project directory using your preffered terminal. Next, run the command
npm init -y
This will create a package.json
file, which
is required for PostCSS to work. We will come back to
this file later.
Now run
npm install --save-dev postcss postcss-cli
This commmand creates a
node_modules
directory, installs PostCSS
and the PostCSS CLI into it, and also creates a
package-lock.json
file. We don't need to do
anything with the node_modules
folder or
package-lock.json
, they are just needed for
PostCSS.
Next, create a file named
postcss.config.js
. In this file we will
list all the PostCSS plugins we install.
Installing plugins
You install a plugin (full list of plugins here) the same way you installed PostCSS and the PostCSS CLI, like this:
npm install --save-dev <plugin name>
which can actually be shortened to
npm i -D <plugin name>
For example, to install the cssnano plugin which minifies your css for faster load times, you would run:
npm i -D cssnano
then, in the postcss.config.js
file add
this boilerplate:
module.exports = {
map: {},
plugins: [
],
};
Let's break this down.
map: {}
is where you put the options for
generating
source maps.
The only option I change is setting the inline attribute
to false, like this:
map: {inline: false}
This disables the default inline source map which is
stored as a base64 encoded string at the bottom of the
output CSS file, and instead creates a separate source
map with the extention
.css.map
plugins: []
is where you list the plugins
you install, in this format:
plugins: [
require("<plugin1>")(),
require("<plugin2>")(),
etc.
]
Some plugins have options which you would put in the second set of brackets, after the plugin name, but many don't.
For example if I have installed cssnano and
autoprefixer
(which adds vendor prefixes for you), and don't want an
inline source map, my
postcss.config.js
file would look like
this:
module.exports = {
map: {inline: false},
plugins: [
require("cssnano")(),
require("autoprefixer")()
],
};