Installing and running postcss-cli
PostCSS itself is a JavaScript library. To run it from a terminal you need postcss-cli: it reads a CSS file, passes it through plugins and writes the result. You need Node.js 20 or newer.
Installing
Create a folder for the blog and install PostCSS, its CLI and a first plugin — Autoprefixer:
mkdir blog
cd blog
npm init -y
npm pkg set type=module
npm install --save-dev postcss postcss-cli autoprefixer
npx postcss --versionThe second npm command turns on ES modules (import/export) — you will need them for the config file in the next lesson. The last command prints the postcss-cli version, for example 12.0.0.
Project structure
Source styles live in styles/, processed ones go to css/, and the page links only css/main.css:
blog/
├── index.html
├── css/
│ └── main.css ← written by PostCSS
├── styles/
│ └── main.css ← edited by you
└── package.jsonCreate styles/main.css:
/* styles/main.css */
.post-card {
padding: 16px;
user-select: none;
}First run
The command takes the source file, the output path after -o and plugins after -u (for use):
npx postcss styles/main.css -o css/main.css -u autoprefixerThe file css/main.css appears:
.post-card {
padding: 16px;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLC... */The last line is an inline source map (shortened here). postcss-cli adds it by default; the source maps lesson covers it. The --no-map flag turns it off.
Without -o the result is printed to the terminal — handy for experiments:
npx postcss styles/main.css -u autoprefixer --no-mapWatching for changes
The --watch flag keeps the program running and processes the file after every save:
npx postcss styles/main.css -o css/main.css -u autoprefixer --watchStop watching with Ctrl+C.
Scripts in package.json
To avoid typing flags every time, save the commands in package.json:
{
"scripts": {
"css:dev": "postcss styles/main.css -o css/main.css -u autoprefixer --watch",
"css:build": "postcss styles/main.css -o css/main.css -u autoprefixer --no-map"
}
}Now run npm run css:dev while working and npm run css:build before publishing. Inside scripts you do not need npx.
Several files
With several source files, give an output folder with --dir instead of -o:
npx postcss styles/*.css --dir css -u autoprefixerCommon mistake
Listing a plugin in -u but forgetting to install it. The command stops with a message that starts with Plugin Error: Cannot find package 'autoprefixer'. Every plugin is a separate npm package: first npm install --save-dev plugin-name, then run.