What is PostCSS?
In a nutshell
PostCSS is a tool for transforming CSS with JavaScript.
As the docs say, PostCSS takes your CSS files, converts them into an Abstract Syntax Tree (AST) and feeds it through plugins to modify the output:
PostCSS takes a CSS file and provides an API to analyze and modify its rules (by transforming them into an Abstract Syntax Tree). This API can then be used by plugins to do a lot of useful things, e.g., to find errors automatically, or to insert vendor prefixes.
Currently, PostCSS has more than 200 plugins. You can find all of the plugins in the plugins list. Below is a list of our favorite plugins — the best demonstrations of what can be built on top of PostCSS.
Popular plugins include:
autoprefixer
: adds vendor prefixes.postcss-nested
: lets you nest selectors in your CSS much like in SASS.- postcss-modules: lets you use CSS modules.
Setup
CLI / NPM script
Install the postcss-cli
package and whatever plugins you need:
npm i -D postcss-cli autoprefixer postcss-nested
Create postcss.config.js
:
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: [
require('autoprefixer'),
require('postcss-nested')
]
}
module.exports = config
Run postcss:
postcss -w -o main.css css/*.css
Webpack
Use postcss-loader
in webpack.config.js
:
module.exports = {
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
}
},
{
loader: 'postcss-loader'
}
]
}
]
}
}
Then create postcss.config.js
:
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: [
require('autoprefixer'),
require('postcss-nested')
]
}
module.exports = config
Sources/links
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment