Translator: The boy ABU DX

The original link

Translator’s note: If there is any improper translation of this article, please contact the translator. Please supervise.

We’ve featured PostCSS on SitePoint several times before, but it still stumped a lot of people. To sum up PostCSS in one sentence:

PostCSS handles a lot of tedious work that you don’t have to do

It subtly differentiates itself from the preprocessor by offering optional and more concise programming languages to compile into CSS, such as Sass, Less, and Stylus. Part of the reason for this conclusion:

  • Its name. PostCSS can perform operations on files both before and after the preprocessor compiles source code into CSS.
  • PostCSS _ can _ replace your preprocessor. There are many plug-ins that implement designs such as variables, nesting, mixins, and extends.

However, while you can build your own preprocessor, there is no reason to do so unless you want to limit functionality and speed up compilation. Personally, TO enhance CSS, I use Sass, supplemented by PostCSS.

How do I use PostCSS?

PostCSS can be used in standalone JavaScript files as well as Gulp, Grunt, Broccoli, Brunch and many other task runners I’ve never heard of

PostCSS itself is only responsible for parsing CSS into JavaScript objects and tokens. The magic of plug-ins that check, modify, add, or modify properties and property values happens before the final CSS file is written.

To use PostCSS in Gulp, you need to set up your project and install two modules:

npm init
npm install --save-dev gulp gulp-postcss
Copy the code

Then, you can continue to add the plug-ins you need, such as autoprefixer and CSsnano.

npm install --save-dev autoprefixer cssnano
Copy the code

You can create a gulpfile.js file. It defines a task that loads the CSS source file and then passes through the PostCSS pipe. The plug-in and any other options required are passed to PostCSS in an array. Finally, the CSS file is exported to the target file.

/ / Gulp. Js configuration
var gulp = require('gulp'),
    postcss = require('gulp-postcss');

// Apply the PostCSS plugin
gulp.task('css'.function() {
  return gulp.src('src/main.css')
    .pipe(postcss([
      require('autoprefixer') ({}),require('cssnano')
    ]))
    .pipe(gulp.dest('dest/main.css'));
});
Copy the code

From the console, you can run the task using the following command:

gulp css
Copy the code

Now all we need is a handy list of PostCSS plug-ins.

1. Autoprefixer

If you don’t use other plug-ins, install Autoprefixer.

npm install --save-dev autoprefixer
Copy the code

As browsers become better at supporting the specification, vendors choose alternatives such as toggle-based attribute enablers, and browser-specific prefixes such as -webkit-, -moz-, and -ms- are dying out. Unfortunately, you can’t avoid using vendor prefixes, but it’s hard to know which prefixes are needed all the time (user-select, for example), which occasionally (3D transformation, for example), and which never (border-radius, for example).

With Autoprefixer, you no longer need to worry about prefix selection. You just need to define prefix-free CSS, then declare the browser you want to support, Autoprefixer will check caniuse.com when adding the necessary prefixes. The following code specifies the latest 2 versions of any major browser, or any browser with more than 2% market share:

.pipe(postcss([
  require('autoprefixer') ({browsers: ['last 2 versions'.'> 2%']})))Copy the code

In the library functions of the preprocessor, this is an advanced option that requires special encoding and applies the vendor prefix in any case. As browser standards evolve, your prefixed code will be removed when you run PostCSS in the future.

Autoprefixer is so useful and pervasive that you may already be using it without realizing it is a PostCSS plug-in.

2. PostCSS Assets

PostCSS Assets provide a number of useful image manipulation functions:

npm install --save-dev postcss-assets
Copy the code

Its options include:

  • Reduction URL:Given a file name, PostCSS Assets are replaced with either a root path or a perfectly valid URLresolve(image).
  • Processing size:PostCSS Assets are replaced with an equivalent pixel valuewidth(image).height(image)size(image).
  • Inline image:PostCSS Assets are replaced with Base64 encoded stringsinline(image).
  • Clear the cache: PostCSS Assets adds a random query string to the image reference to confirm that the latest file is loaded.

3. cssnext

Cssnext lets you use the latest CSS syntax now.

npm install --save-dev postcss-cssnext
Copy the code

The plugin has a long list of features, including:

  • varvariable
  • #rrggbbaacolor
  • The color function
  • The filter
  • The fallback

When it executes, CSSNext translates the code into the syntax supported by today’s browsers.

4. Rucksack

Rucksack provides many functions that its developers claim will make CSS development fun again.

npm install --save-dev rucksack-css
Copy the code

Its options include:

  • Responsive typography, just a simplefont-size: responsiveDeclare, you can automatically adjust font size and line height.
  • A large number of pseudo-selectors, such asli:at-least(4), select any list with at least four entries.
  • Property alias, as used in your CSSbgInstead ofbackground.
  • A number of predefined easing functions.

5. Stylelint

Stylelint reports errors based on 140 rules that are designed to catch common errors, implement style protocols, and enforce best practices. There are a number of options available to configure Stylelint to your liking — Pavels Jelisejevs articles use PostCSS to improve the quality of your CSS and take you through the build process.

6. CSS MQPacker

MQPacker queries your media as a rule if necessary:

npm install --save-dev css-mqpacker
Copy the code

Preprocessors such as Sass can use media queries in a statement, as simple as:

.widget1 { width: 100%; @media (min-width: 30em) { width: 50%; } @media (min-width: 60em) { width: 25%; } } .widget2 { width: 100px; @media (min-width: 30em) { width: 200px; }}Copy the code

This compiles to:

.widget1 { width: 100%; }

@media (min-width: 30em) {
  .widget1 { width: 50%; }}@media (min-width: 60em) {
  .widget1 { width: 25%; }}.widget2 { width: 100px; }

@media (min-width: 30em) {
  .widget2 { width: 200px; }}Copy the code

To reduce file size and (as much as possible) improve parsing time, MQPacker packs multiple declarations into a single @media rule, namely:

.widget1 { width: 100%; }
.widget2 { width: 100px; }

@media (min-width: 30em) {
  .widget1 { width: 50%; }
  .widget2 { width: 200px; }}@media (min-width: 60em) {
  .widget1 { width: 25%; }}Copy the code

Reliable intelligence: Make sure that the first media query declaration in your code defines all possible options in the order you want them to be, even if there are no actual differences. This ensures that MQPacker defines the rules in the correct order.

MQPacker also provides the option to sort media queries with output sourcemap.

7. cssnano

Cssnano compresses your CSS files to ensure as few downloads as possible in the development environment. Install it with the following command:

npm install --save-dev cssnano
Copy the code

The plugin works by removing comments, whitespace, duplicate rules, outdated browser prefixes, and other optimizations, generally reducing the size by at least 50%. There are many other options, but CS Nano is one of the best. Use it!

What else?

A searchable index of postCSS plug-ins is available on postcss.parts, and the PostCSS Usage document also provides a list of suggested options. Plug-ins can be found for just about any CSS job you can think of, but be aware of the crossover and duplication issues — cSSNext also includes Autoprefixer, for example.

If that’s not enough, you can also develop your own PostCSS plugin in JavaScript. The PostCSS documentation explains how to write a plug-in and provides a reference API.

PostCSS makes CSS development easier, whether you use a preprocessor or not. The CSS development time it saves is much more important than the initial installation and configuration effort.