search
HomeWeb Front-endJS TutorialHow to Build Your Own CSS Preprocessor With PostCSS

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

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%'] })
    ];

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/'));
});

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%'] })
    ];

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;
    }
}

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;
}

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
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor