Home > Web Front-end > JS Tutorial > How to Build Your Own CSS Preprocessor With PostCSS

How to Build Your Own CSS Preprocessor With PostCSS

William Shakespeare
Release: 2025-02-20 08:37:09
Original
369 people have browsed it

How to Build Your Own CSS Preprocessor With PostCSS

Key Points

  • PostCSS allows developers to build their own CSS preprocessors, providing greater flexibility and control over other preprocessors such as Sass, LESS or Stylus. It uses JavaScript plugin to manipulate styles and is able to add preprocessor-like features such as variables, mixins, and nesting.
  • The advantages of PostCSS include modularity, lightweight builds, instant implementation of new features, and the ability to enforce development strategies. It is also faster than traditional preprocessors. However, it also has some disadvantages, such as the increased complexity of the build process, different syntax, and the requirements for effective CSS.
  • While PostCSS has great potential, it may not be suitable for all projects. It can be an attractive option for small, simple projects or single teams. But for large teams or projects, existing preprocessors may still be the first choice due to the wide understanding and use of Sass.

Many developers have adopted LESS, Stylus or the most popular Sass at present. Ideally, you should also post-process your CSS using Autoprefixer to add vendor prefixes when needed without using frameworks like mixin or Compass. Autoprefixer is a plugin for PostCSS; it is a tool for converting CSS into an object model that can be used to manipulate styles. There are many other available plugins that implement preprocessor-like features such as variables, mixins, and nesting. Ben Frain's recent article "Breaking Up with Sass: Not You, It's Me" puts forward an interesting proposition. Given that you can use PostCSS to create the CSS preprocessor you want, do you really need Sass, LESS or Stylus? A basic Sass-like parser can be created during your build process. In this example, I'll use a Gulp.js task file, but the same concept applies to Grunt or any other build system. First, we use npm to install PostCSS and the required plugins, for example:

npm install gulp-postcss postcss-mixins postcss-simple-vars postcss-nested autoprefixer-core --save-dev
Copy after login

Then create an array of CSS processing functions in gulpfile.js, for example:

var
    gulp = require('gulp'),
    postcss = require('gulp-postcss'),
    processors = [
        require('postcss-mixins'),
        require('postcss-simple-vars'),
        require('postcss-nested'),
        require('autoprefixer-core')({ browsers: ['last 2 versions', '> 2%'] })
    ];
Copy after login

and write a CSS processing task, for example:

// 编译CSS
gulp.task('css', function() {
  return gulp.src('source/css/styles.css')
    .pipe(postcss(processors))
    .pipe(gulp.dest('dest/styles/'));
});
Copy after login

You can also use the PostCSS API to create your own processing functions. For example, we can apply a sans-serif fallback for all font-family declarations:

processors = [
        require('postcss-mixins'),
        require('postcss-simple-vars'),
        require('postcss-nested'),
        function(css) {
            // sans-serif 后备
            css.eachDecl('font-family', function(decl) {
                decl.value = decl.value + ', sans-serif';
            });
        },
        require('autoprefixer-core')({ browsers: ['last 2 versions', '> 2%'] })
    ];
Copy after login

If the file /source/css/styles.css contains the following code:

$colorfore: #333;
$colorback: #fff;

@define-mixin reset {
    padding: 0;
    margin: 0;
}

main {
    font-family: Arial;
    @mixin reset;
    color: $colorfore;
    background-color: $colorback;

    article {
        color: $colorback;
        background-color: $colorfore;
    }
}
Copy after login

Running gulp css will create this CSS in /dest/css/styles.css:

main {
    font-family: Arial, sans-serif;
    padding: 0;
    margin: 0;
    color: #333;
    background-color: #fff;
}

main article {
    color: #fff;
    background-color: #333;
}
Copy after login

Advantages

PostCSS allows you to get rid of the restrictions and choices imposed by preprocessor authors. This method provides several benefits:

  • Modular You just need to add the required plugins and functions for your project.
  • LightweightPreprocessors are becoming increasingly large and complex. You may not want or use every feature, but they still exist. PostCSS reduces volume.
  • Instant implementation Have you ever waited for certain features to be available in Sass, LibSass, LESS, Stylus, or other preprocessors? You can use now...
  • JavaScript Functions Your CSS preprocessor uses JavaScript—a real programming language (although some say so!). Most preprocessor language structures are basic. You often see more complex and difficult-to-understand functions and mixins than the original CSS they create. With PostCSS, you can easily open files, read from databases, issue HTTP requests, or perform complex calculations.
  • Enforce development strategies Suppose you want your team to avoid using @extend statements. Unless they add an extend plugin to the build process, @extend will not be available to anyone. This will be immediately obvious.
  • It's fast - very fast The author estimates PostCSS is 4-40 times faster than equivalent preprocessors. If only a few plugins were needed, I think the benefits would be higher. The entire solution is built in JavaScript and does not need to jump to another library or language interpreter.

Disadvantages

So everything is OK? Unfortunately, PostCSS is not the perfect solution:

  • Increased complexity Your build process will become more difficult to manage. Adding Sass is usually a line or two of code, but PostCSS requires more planning – especially since plugins have to be called in a specific order. For example, @import inline should be parsed before parsing the variable. But what if your @import declaration contains variables? In some cases, it may be necessary to call the plugin multiple times.
  • Different syntax I initially tried to convert a small Sass project to PostCSS. Don't even try it! Although I ended up succeeding, PostCSS plugins often use slightly different syntaxes like @define-mixin instead of @mixin. This can lead to obfuscation and a lot of code updates. Part of the reason is...
  • PostCSS requires valid CSS Most preprocessors parse plain text files, so any syntax is theoretically possible. PostCSS creates an object model, so it requires syntactically correct CSS from the beginning. Even a // single line comment can cause it to fail. You can preprocess your CSS files before passing them to PostCSS, but then you're back to using the preprocessor!

Should you give up on your preprocessor?

If you start a small, relatively simple standalone project on a single team, a custom PostCSS processor can be an attractive option. I also recommend PostCSS for any real postprocessing tasks such as vendor prefix, packaging media queries into a single declaration, reducing calc() equations, backing up for old browser applications, supporting CSS4 selectors , shrink, etc. There is no benefit in doing these tasks yourself. However, Sass has reached critical mass. No preprocessor syntax is perfect, but it will be understood by most developers on your team. Any subtle difference is unlikely to provide significant benefits or appeal to everyone. That is, PostCSS and similar Rework frameworks have great potential. If a modular CSS plug-in system can replicate - or even mix - the syntax and functionality of Sass, LESS and Stylus we want, we will have a preprocessor that can beat all other preprocessors utensil. You can bet that someone is developing this project now...

Did you successfully use PostCSS as a preprocessor for your project? Does it attract you away from Sass? Will you migrate from LESS? Will you give up on Stylus?

FAQs about PostCSS

What is the main difference between PostCSS and other CSS preprocessors?

PostCSS is a tool that uses JavaScript plugin to convert styles. These plugins can perform various tasks such as code sorting, adding vendor prefixes, and even enabling future CSS capabilities. Unlike other CSS preprocessors like Sass or Less, PostCSS does not have built-in syntax. Instead, it uses plugins to convert CSS. This makes it more flexible and customizable as you can select only the plugins you need for your project.

How to install and use PostCSS?

To install PostCSS, you need to install Node.js and npm on your computer. Then, you can install PostCSS globally using the command

. To use PostCSS, you need to install the plugin you want to use and then create a configuration file that specifies the plugin you want to use. Then, you can run PostCSS on your CSS file using the command npm install -g postcss-cli. postcss input.css -o output.css

What are some popular PostCSS plugins?

There are many PostCSS plugins available, each with a different purpose. Some popular plugins include Autoprefixer, which automatically adds vendor prefixes to your CSS; cssnext, which allows you to use future CSS features today, and cssnano, which reduces your CSS for production environments.

Can I use PostCSS with other CSS preprocessors?

Yes, you can use PostCSS with other CSS preprocessors like Sass or Less. This allows you to take advantage of the capabilities of these preprocessors while also benefiting from the flexibility and power of PostCSS.

What are the benefits of using PostCSS?

PostCSS provides many benefits. It is highly customizable, allowing you to select only the plugins you want. This can lead to a smaller, faster build process. PostCSS also enables you to use future CSS features today, and it automatically adds vendor prefixes to your CSS, saving you time and ensuring your style works properly in different browsers.

What are the disadvantages of using PostCSS?

While PostCSS is powerful and flexible, its learning curve may be steeper than other CSS preprocessors. Because it relies on plugins, you need to spend time researching and choosing the right plugin for your project. Also, because it is a newer tool, it may not be as widely supported or adopted as other preprocessors.

How does PostCSS handle mixin?

PostCSS handles mixin through the postcss-mixins plugin. This plugin allows you to define and use mixins in CSS, similar to what you do in Sass or Less. You can define a mixin in the PostCSS configuration file and use it in your CSS using the @mixin keyword.

Can I use PostCSS in my existing project?

Yes, you can integrate PostCSS into your existing projects. You just need to install PostCSS and the plugin you want to use, and then set up a PostCSS configuration file. You can then run PostCSS on the existing CSS file.

How does PostCSS compare to other tools like Autoprefixer or cssnext?

Autoprefixer and cssnext are actually PostCSS plugins. This means they are tools that run on top of PostCSS, leveraging its plug-in architecture. Autoprefixer adds vendor prefix to your CSS, while cssnext allows you to use future CSS features today.

Is PostCSS suitable for large projects?

Yes, PostCSS is suitable for projects of any size. Because it is customizable, you can select only the plugins you want, enabling a smaller, faster build process. This makes it a good choice for large projects where performance is an issue.

The above is the detailed content of How to Build Your Own CSS Preprocessor With PostCSS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template