Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Other useful plugins

PostCSS has hundreds of plugins, but most projects are fine with the chain from the previous chapter. Below are a few tools you will meet more often than others, and one idea that is easy to show with an example.

postcss-pxtorem: px to rem

The rem unit is relative to the font size of the root element. If a user enlarges the font in browser settings, sizes in rem grow with it, while sizes in px do not. The postcss-pxtorem plugin lets you write familiar pixels and get rem:

npm install --save-dev postcss-pxtorem
// postcss.config.js
import pxtorem from 'postcss-pxtorem';
 
export default {
  plugins: [pxtorem()],
};
/* styles/main.css */
.post-title {
  font-size: 24px;
  margin-bottom: 16px;
  border: 1px solid #ddd;
}
.post-title {
  font-size: 1.5rem;
  margin-bottom: 16px;
  border: 1px solid #ddd;
}

By default the plugin divides by 16 (the rootValue option) and changes only the font, line-height and letter-spacing properties (the propList option). To convert every property except thin borders, pass options:

// postcss.config.js
import pxtorem from 'postcss-pxtorem';
 
export default {
  plugins: [pxtorem({ propList: ['*'], minPixelValue: 2 })],
};
.post-title {
  font-size: 1.5rem;
  margin-bottom: 1rem;
  border: 1px solid #ddd;
}

minPixelValue: 2 leaves values below 2 pixels as they are, so the 1px border did not turn into a fractional rem.

A few more tools

PackageWhat it does
@fullhuman/postcss-purgecssRemoves selectors that do not appear in your HTML and JS files
postcss-scssA syntax that lets PostCSS parse SCSS files
postcss-sort-media-queriesGroups identical media queries together and sorts them
stylelintChecks styles for errors, a separate program

PurgeCSS helps when you include a big library like Bootstrap but use a small part of its classes. Configure it carefully: it may treat classes added by JavaScript as unused.

Stylelint is a separate tool

Stylelint is a linter — a program that looks for errors and style-rule violations in CSS. It parses styles with the PostCSS parser, but it does not go into postcss.config.js: it changes nothing in the output, it only reports problems. You install and run it separately:

npm install --save-dev stylelint stylelint-config-standard

Create .stylelintrc.json in the project root:

{
  "extends": "stylelint-config-standard"
}
npx stylelint "styles/**/*.css"

The command prints a list of findings with line numbers, for example about an unknown property or a duplicate selector. The --fix flag fixes what can be fixed automatically.

Common mistake

Adding a plugin for every small thing. Each extra plugin slows the build down and needs updates. Before installing a new package, check whether postcss-preset-env or the browser itself can already do it.

Thanks for reading!

Donate to the site — we work hard for you.