Post2Video

How to Use PostCSS With Stylesheets : A Quick Guide

Posted on Dec 31, 2023 By Nathan Krasney
How to Use PostCSS With Stylesheets : A Quick Guide

Table of Contents

What is PostCSS

  • A tool for transforming CSS with JavaScript
  • very popular- more than 77m weekly downloads (Jan 2023)
  • The postcss workflow can be described as follows
    postcss workflow

Motivation for PostCSS

PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more

How to invoke PostCSS

  • Install postcss and postcss plugins (both using -D)
  • create configuration file - postcss.config.js with postcss plugins
  • run postcss from the command line as part of your build process
check Repositories

Next.js and vite support for PostCSS

Next.js compiles CSS for its built-in CSS support using PostCSS. Check next.js documentation

It is applied automatically to all imported CSS if the vite project contains valid PostCSS config (any format supported by postcss-load-config, e.g., postcss.config.js). Check vite documentation

Repositories

The following are repositories with sample code

post-css-playground

post-css-playground is a Vanila js repo with postcss

Motivation

Experiment with postcss using the plugins nanocss and postcss-preset-env via postcss.config.js. postcss-cli invokes postcss via the package.json scripts

Points of interest

  • Use packages postcss and postcss-cli to invoke the postcss plugin nanocss.
  • Install packages postcss , postcss-cli and nanocss as dev dependencies because postcss is done on development
  • Compare the size of styles.css before nanocss minimizing - 163B with the CSS file in dist after nanocss processing - 39B. These files are the same concerning the view
  • Use postcss-preset-env here to convert CSS nesting to CSS format known to most browsers (e.g. CSS nesting is supported in chrom 120; check mdn documentation)

post-css-vite-playground

Motivation

In post-css-playground, you must install the packages postcss and postcss-cli and call postcss in the package.json script. You do this to invoke the plugins in postcss.config.js

But in vite project, part of this is done out of the box, i.e., you do not need to install the packages postcss and postcss-cli, and you do not need to call postcss in package.json

Points of interest

  • There is no need to use nanocss explicitly because vite minimizes the CSS out of the box. simply do 'npm run build' and look inside the dist/assets directory
  • No need to use postcss-preset-env explicitly to translate nesting to a format known to the old browser. do 'npm run build' and look inside the dist/assets directory

References