SoFunction
Updated on 2025-04-04

Detailed explanation of postcss installation and use examples

PostCSS is a set of tools used to change CSS using JS plugins. These plugins can support variables and mixed syntax, convert future CSS syntax, inline pictures, and more

We have used tools such as Less and SASS to preprocess CSS, write according to the syntax they agreed upon and eventually convert it into available styles. The price of this is that we must first be familiar with the writing grammar of this tool.

With the rise of automation tools such as Grunt, Gulp, and Webpack in recent years, combined applications have become very popular. So what is the meaning of PostCSS? The answer is: CSS ecosystem

PostCSS has a lot of plug-ins, such as autoprefixer, which automatically adds browser prefix to CSS, the most commonly used px to rem plug-in px2rem on mobile, and also supports cssnext, which has not yet become the CSS standard but is available, and many more. Even the famous Bootstrap in the next version of Bootstrap 5 will use PostCSS as the basis for the style.

To summarize PostCSS in one sentence: What the CSS compiler can do, it can do it, and it can do it better.

1. PostCSS installation

Installing PostCSS usually involves using JavaScript package managers such as npm (Node Package Manager) or yarn. Here are the basic steps for installing using npm:

1. Make sure the environment is ready:

First, make sure that the environment is installed, you can run node -v and npm -v from the terminal or command prompt to confirm that the npm version is properly installed and available.

2. Initialize the project (if not already init):

If you are in a new project and have no files, you can run the npm init command to create a new project.

3. Install PostCSS:

Open a terminal or command prompt in the project root directory, and run the following command to install PostCSS as a development dependency:

npm install postcss --save-dev

4. Select and install plug-ins:

The core of PostCSS itself does not contain any specific CSS processing functions. Its power is that it has many optional plug-ins, such as Autoprefixer (used to automatically add browser prefixes), PreCSS (supports preprocessors such as Sass-like syntax). Install the required plugins according to your needs, for example:

   npm install autoprefixer --save-dev

2. Use PostCSS

1. Configure PostCSS:

Create a PostCSS configuration file such as ., or , specifying the plugin to use and its options. For example, in:

    = {
     plugins: [
       require('autoprefixer')({
         /* autoprefixer configuration options */
       }),
       // Other plugins...     ]
   };

2. Integrate into the build tool:

To apply PostCSS in a real project, it is usually used in conjunction with build tools such as Webpack, Gulp, Grunt, or Rollup. For example, in Webpack, configure the loader to process the CSS file and point to PostCSS:

   // 
    = {
     module: {
       rules: [
         {
           test: /\.css$/,
           use: [
             'style-loader',
             'css-loader',
             {
               loader: 'postcss-loader',
               options: {
                 postcssOptions: { // Or directly refer to the config file path: 'config': './path/to/'                   plugins: [require('autoprefixer')]
                 }
               }
             }
           ]
         }
       ]
     }
   };

3. Run the compilation:

When the above configuration is set, when you run the build command, Webpack or other build tools will automatically call PostCSS to process the CSS files, and the conversion functions provided by the application plug-ins.

4. Manual compilation:

For stand-alone use cases, you can write a script to call the PostCSS CLI to compile the CSS file, as mentioned earlier:

   postcss src/ -o build/

3. Use PostCSS with the construction tool

integrated

In web development, PostCSS is often used in integration with construction tools such as Webpack. In the configuration file() of Webpack, you need to set the corresponding loader to process the CSS file and introduce the PostCSS-loader:

// 
const path = require('path');
 = {
  // ...Other configuration items...  module: {
    rules: [
      {
        test: /\.css$/, // Match .css file        use: [
          'style-loader', // Inject CSS into JS to load dynamically to the page          'css-loader', // Syntax that cannot be recognized by parsing imports and other loaders in CSS files          {
            loader: 'postcss-loader', // Introduce PostCSS-loader            options: {
              postcssOptions: {
                config: (__dirname, ''), //Introduce PostCSS configuration file              },
            },
          },
        ],
      },
    ],
  },
  // ...Other configuration items...};

2. Write PostCSS configuration file

Create a PostCSS configuration file (for example) in the project, defining the plugin used and its options:

// 
 = {
  plugins: [
    // Automatically add CSS prefix    require('autoprefixer')({
      overrideBrowserslist: ['last 2 versions'],
    }),
    // Convert px to vw (responsive unit conversion)    require('postcss-px-to-viewport')({
      viewportWidth: 750, // Window width      unitPrecision: 3, // Unit conversion accuracy      viewportUnit: 'vw', // Converted units      selectorBlackList: ['.ignore'], // Class name that is not converted      minPixelValue: 1, // Minimum conversion value      mediaQuery: false, // Is it also converted in media query    }),
    // CSS optimization    require('cssnano')({
      preset: 'default', // Use the default optimized configuration    }),
  ],
};

3. Manually process CSS files

If you do not use the build tool, you can directly process CSS files through the PostCSS command line interface (CLI):

npx postcss  -o  --config 

In this command, it is the source file, the output file processed by PostCSS. The --config parameter specifies the location of the configuration file.

4. Recommended and examples of PostCSS plug-in

The power of PostCSS lies in its rich plug-in ecosystem. Here are some commonly used PostCSS plug-ins and their main functions:

Autoprefixer:

Features: Automatically add appropriate vendor prefixes to CSS style rules to ensure compatibility.
Install and use: npm install autoprefixer --save-dev and enable it in the configuration file.

PreCSS:

Function: Allows the use of features such as Sass and Less in CSS, such as variables, nested rules, mixed macros, etc.
Install and use: npm install precss --save-dev and add the plugin in the PostCSS configuration.

PostCSS-Preset-Env:

Features: Enables you to use future CSS specification draft features and automatically translate to currently available CSS syntax based on the support of the target browser.
Install and use: npm install postcss-preset-env --save-dev, and configure the corresponding browser compatibility target.

PostCSS-Nested:

Features: Allows the use of nested CSS rules to improve code organization and readability.
Install and use: npm install postcss-nested --save-dev, and enable it in the configuration file.

PostCSS-Calc:

Function: Enhance the calc() function in CSS to handle more complex computational expressions.
Install and use: npm install postcss-calc --save-dev and add to the PostCSS plugin list.

PostCSS-Custom-Properties (also known as CSS Variables):

Features: Supports CSS custom properties (CSS Variables), making it possible to use variables in CSS.
Install and use: npm install postcss-custom-properties --save-dev, and enable this plugin.

PostCSS-Color-Function:

Function: Allows the use of color functions such as HSLA, RGBA, etc. to create and transform color values.
Install and use: npm install postcss-color-function --save-dev and add it to the PostCSS configuration.

CSSNano:

Features: CSS code compression and optimization tools to reduce the size of the final output CSS file.
Installation and use: npm install cssnano --save-dev, which is generally enabled in a production environment to optimize the production environment's CSS resources.

Each plugin needs to be properly configured and introduced in the PostCSS configuration file for effective during the build process. Be sure to consult the official documentation for each plugin for a more detailed installation and configuration guide.

5. PostCSS combined with construction workflow

In addition to the above-mentioned integration with build tools such as Webpack, PostCSS can also be used with a variety of different build systems and task runners, such as:

Gulp

In the Gulp build system, you can use the gulp-postcss plugin to process CSS files:

// Make sure you have installed the necessary plug-insnpm install gulp-postcss gulp-sourcemaps autoprefixer --save-dev
// Configure PostCSS tasks invar gulp = require('gulp');
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
('process-css', function () {
  var processors = [
    require('autoprefixer')({/* autoprefixer option */}),
    // Add other required PostCSS plugins  ];
  return ('src/**/*.css')
    .pipe(()) // Initialize the source map    .pipe(postcss(processors)) // Run PostCSS processing    .pipe(('.')) // Write out the source map file    .pipe(('dist')); // Output processed CSS files to the dist directory});

Grunt

In the Grunt build tool, you can use the grunt-postcss plugin to perform PostCSS tasks:

// Make sure you have installed the necessary plug-insnpm install grunt-postcss autoprefixer --save-dev
// Configure PostCSS tasks in = function(grunt) {
  ('grunt-postcss');
  ({
    postcss: {
      options: {
        map: true, // Generate sourcemaps        processors: [
          require('autoprefixer')({/* autoprefixer option */}),
          // Add other required PostCSS plugins        ]
      },
      dist: {
        src: 'src/**/*.css',
        dest: 'dist/'
      }
    }
  });
  ('default', ['postcss']);
};

Rollup

For applications that use Rollup for module packaging, PostCSS can be integrated through the rollup-plugin-postcss plugin:

// Make sure you have installed the necessary plug-insnpm install rollup-plugin-postcss autoprefixer --save-dev
// Configure PostCSS plug-in inimport postcss from 'rollup-plugin-postcss';
export default {
  input: 'src/',
  output: {
    file: 'dist/',
    format: 'iife'
  },
  plugins: [
    postcss({
      extensions: ['.css'], // What files with extensions are processed      extract: 'dist/', // Extract CSS to separate files      plugins: [
        require('autoprefixer')({/* autoprefixer option */})
        // Add other required PostCSS plugins      ]
    })
  ]
};

In short, no matter which build tool, PostCSS can be flexibly integrated into it and exert its powerful CSS processing capabilities.

6. PostCSS development practice

1. Real-time updates during development:

During the development process, in order to achieve real-time preview of CSS effects, tools such as browser-sync can be combined with PostCSS to automatically refresh the browser page when the CSS file changes.

   // Example: Combining browser-sync with PostCSS in Gulp   var browserSync = require('browser-sync').create();
   ('serve', function() {
     ({
       server: {
         baseDir: './dist'
       }
     });
     ('src/**/*.css', ('process-css', ));
   });

2. Style checking and standardization:

Using plugins such as stylelint, stylefmt, etc., you can perform CSS code style checksum formatting in the PostCSS pipeline.

   // Add stylelint and stylefmt in PostCSS configuration file    = {
     plugins: [
       require('stylelint')(), // CSS code style check       require('stylefmt')({ /* stylefmt option */ }), // Format CSS code       // Other plugins...     ]
   };

Modules:

PostCSS can also support CSS Modules through plugins such as postcss-modules, which helps prevent style naming conflicts and implement local scopes.

   //Enable CSS Modules in Webpack configuration   {
     test: /\.css$/,
     use: [
       'style-loader',
       'css-loader?modules',
       {
         loader: 'postcss-loader',
         options: {
           postcssOptions: {
             plugins: [
               require('postcss-modules')()
             ]
           }
         }
       }
     ]
   }

4. Topic and variable management:

With plugins like postcss-simple-vars or postcss-custom-properties, variables can be declared and used in CSS for easy management and switching topics.

-in-JS support:

Some frameworks or libraries such as styled-components have integrated PostCSS processing mechanisms, which allow developers to write CSS-style logic in JavaScript, and can also enjoy the various benefits brought by PostCSS.

7. Deep integration of PostCSS with other tools

Visual Studio Code integration:

You can implement real-time PostCSS plug-in functions in the editor by installing VS Code extensions such as vscode-postcss-sorting, vscode-stylelint, etc., such as sorting CSS attributes, checking CSS code styles, etc.

IDE integration:

Many modern IDEs such as WebStorm, IntelliJ IDEA, etc. support PostCSS. Users can associate PostCSS with specific plug-ins by configuring the built-in CSS preprocessor settings of the IDE, so as to get real-time feedback when writing and previewing CSS.

Git Hooks:

By integrating PostCSS into your project's Git hooks (such as pre-commit), PostCSS and related plug-ins can be automatically run before submitting your code for code inspection and optimization, ensuring compliance with code specifications and maintain consistency.

Continuous Integration/Continuous Deployment (CI/CD):

In the CI/CD process, automation tasks can be configured to automatically run PostCSS processing CSS files during the build phase to ensure that the published code is always properly converted and optimized.

Component library and design system:

Nowadays, many UI component libraries and design systems such as Ant Design and Material UI are used internally to style and customize, which enhances the flexibility and maintainability of CSS.

Static Site Generator (SSG):

For static site generators such as Jekyll, Hugo, and Gatsby, by integrating PostCSS, CSS code can be automatically converted and optimized during the process of generating the website.

Through these deep integrations, PostCSS is not just a simple CSS processing tool, but a technical means that runs through the entire front-end development process, greatly improving the efficiency and output quality of CSS development. With the development of the front-end community, the functions and application scenarios of PostCSS will become more diverse.

This is the end of this article about the installation and use of postcss. For more related postcss installation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!