Introduction to postcss-cli
PostCSS is a powerful tool for transforming styles with JS plugins. postcss-cli
is a simple command line interface for PostCSS. It allows you to use PostCSS directly in your terminal, making it easier to integrate into build processes and automate CSS processing.
Getting Started
To get started with postcss-cli
, you’ll first need to install it using npm or yarn:
npm install --global postcss-cli
yarn global add postcss-cli
Basic Usage
Here’s a basic example of how to use postcss-cli
to process a CSS file:
postcss input.css -o output.css
This command will take input.css
, process it with any PostCSS plugins you’ve configured, and output the result to output.css
.
Using Plugins
postcss-cli
is extremely powerful when used with PostCSS plugins. Below are examples of how to use different plugins:
Autoprefixer
Autoprefixer adds vendor prefixes to CSS rules using values from Can I Use
. Install and configure it like this:
npm install autoprefixer
postcss input.css --use autoprefixer -o output.css
cssnano
cssnano is a modular minifier for CSS, helping you improve load time. Install and configure it like this:
npm install cssnano
postcss input.css --use cssnano -o output.css
PostCSS Nested
PostCSS Nested helps you write nested CSS rules, similar to what you can do in Sass. Install and configure it like this:
npm install postcss-nested
postcss input.css --use postcss-nested -o output.css
All Together
You can use multiple plugins together. For example, to use Autoprefixer, cssnano, and PostCSS Nested:
npm install autoprefixer cssnano postcss-nested
postcss input.css --use autoprefixer --use cssnano --use postcss-nested -o output.css
Configuration File
Instead of passing options in the command line, you can use a configuration file:
module.exports = {
plugins: [
require('autoprefixer'),
require('cssnano'),
require('postcss-nested')
]
};
Example Application
Let’s create a simple application that uses postcss-cli
with Autoprefixer and cssnano. Here’s the project structure:
.
├── package.json
├── postcss.config.js
├── src
│ ├── input.css
└── dist
In package.json
, add the following scripts:
{
"scripts": {
"build:css": "postcss src/input.css -o dist/output.css"
}
}
Create the following configuration in postcss.config.js
:
module.exports = {
plugins: [
require('autoprefixer'),
require('cssnano')
]
};
In src/input.css
, you can write your CSS:
.example {
display: flex;
transition: all .5s;
}
Run the build script:
npm run build:css
This will process your CSS through Autoprefixer and cssnano, outputting a minified CSS file with vendor prefixes in dist/output.css
.
By mastering postcss-cli
and its plugins, you can write more efficient, maintainable, and optimized CSS for your web projects.
Hash: 610355ba9d4d43adc2fa9d0e16df3ba4a66392d83ae079eea84731e8a83f02f5