Saturday, May 14, 2022
HomeWebsite DesignAn Introduction to PostCSS - SitePoint

An Introduction to PostCSS – SitePoint


CSS preprocessors are widespread, however they’ve some drawbacks. On this introduction to PostCSS, we’ll discover some great benefits of PostCSS, the way it works, and what its in depth vary of plugins can obtain.

The Worth and Limitations of Preprocessors

Most CSS builders are conversant in preprocessors. Instruments together with Sass, Much less, and Stylus launched ideas reminiscent of file partials, nesting, variables, and mixins. Some options are regularly showing in native CSS, however a preprocessor remains to be helpful for managing massive codebases and sustaining type and coding consistency.

It could be tough to think about life with no CSS preprocessor, however there are downsides:

  • Preprocessors usually are not extendable or limitable. Most preprocessors are a black field which offer you a particular set of supported options. It could be potential to put in writing customized capabilities, however performance past the scope of that device is stays unattainable — reminiscent of inlining an SVG as a background picture.

    Equally, you possibly can’t cease builders utilizing choices you’d somewhat keep away from reminiscent of @lengthen or deep nesting. Linting can assist, however it gained’t cease the preprocessor compiling a legitimate file.

  • Preprocessors present their very own syntax. Preprocessor code could resemble CSS, however no browser can parse the file natively. The syntax is totally different and, in case your device adjustments or is unavailable, your code would require updates to make it usable.

The advantages greater than outweigh these dangers, however there may be an alternate …

What’s PostCSS?

PostCSS is not a preprocessor (though it may behave like one). It’s a Node.js device which takes legitimate CSS and enhances it. Even these utilizing Sass, Much less, or Stylus typically run a PostCSS step after the preliminary CSS compilation. You’ll have encountered the PostCSS Autoprefixer plugin which mechanically prepends -webkit, -moz, and -ms vendor prefixes to CSS properties which require them.

By itself, PostCSS does nothing. It’s a parser which tokenizes CSS code to create an summary syntax tree. A plugin can course of this tree and replace properties accordingly. As soon as all plugins have accomplished their work, PostCSS reformats all the things again right into a string and outputs to a CSS file.

Round 350 plugins can be found, and most carry out a single job reminiscent of inlining @import declarations, simplifying calc() capabilities, dealing with picture belongings, syntax linting, minifying, and extra. A extra consumer pleasant plugin search is obtainable on the PostCSS plugins catalogue.

PostCSS advantages embody:

  • You begin with commonplace CSS. PostCSS is to CSS what Babel is to JavaScript. It may well take an ordinary stylesheet which works in current browsers and output CSS which works all over the place — for instance, transpiling the newer inset property again into prime, backside, left, and proper properties. Over time, you might drop this course of as extra browsers help inset.

    Admittedly, some plugins will let you parse preprocessor-like syntax which isn’t commonplace CSS, however you don’t have to make use of them.

  • Use the plugins and options you want. PostCSS is configurable, and you may undertake the plugins you require. For instance, you might help partials and nesting however not allow variables, loops, mixins, maps, and different options obtainable in Sass.

  • Present a customized configuration for each undertaking. A particular person undertaking configuration can improve or scale back the set of plugins used elsewhere. The choices are much more various than any preprocessor.

  • Write your personal PostCSS plugins. A variety of plugins is obtainable for extending syntax, parsing future properties, including fallbacks, optimizing code, processing colours, photos, fonts, and even writing CSS in different languages reminiscent of Spanish and Russian.

    Within the unlikely occasion you possibly can’t discover what you want, you possibly can write your personal PostCSS plugin in JavaScript.

  • You’re probably utilizing PostCSS already. You could possibly take away your preprocessor dependencies for those who’re already operating a PostCSS plugin reminiscent of AutoPrefixer. PostCSS isn’t essentially sooner or extra light-weight than utilizing a preprocessor, however it may deal with all CSS processing in a single step.

Putting in PostCSS

PostCSS requires Node.js, however this tutorial demonstrates the best way to set up and run PostCSS from any folder — even those who aren’t Node.js tasks. You may also use PostCSS from webpack, Parcel, Gulp.js, and different instruments, however we’ll keep on with the command line.

Set up PostCSS globally in your system by operating the next:

npm set up -g postcss-cli

Guarantee it’s working by coming into this:

postcss --help

Putting in Your First PostCSS Plugin

You’ll require a minimum of one plugin to do something sensible. The PostCSS import plugin is an effective choice which inlines all @import declarations and merges your CSS right into a single file. Set up it globally like so:

npm set up -g postcss-import

To check this plugin, open or create a brand new undertaking folder reminiscent of cssproject, then create a src subfolder in your supply recordsdata. Create a foremost.css file to load all partials:


@import '_reset';
@import '_elements';

Then create a _reset.css file in the identical folder:


* {
  padding: 0;
  margin: 0;
}

Comply with this with an _elements.css file:


physique {
  font-family: sans-serif;
}

label {
  user-select: none;
}

Run PostCSS from the undertaking’s root folder by passing the enter CSS file, a listing of plugins to --use, and an --output filename:

postcss ./src/foremost.css --use postcss-import --output ./types.css

In the event you don’t have any errors, the next code shall be output to a brand new types.css file within the undertaking root:



* {
  padding: 0;
  margin: 0;
}

physique {
  font-family: sans-serif;
}
label {
  user-select: none;
}
/* sourceMappingURL=information:software/json;base64,...

Word that PostCSS can output CSS recordsdata anyplace, however the output folder should exist; it is not going to create the folder construction for you.

Enabling and Disabling Supply Maps

An inline supply map is output by default. When the compiled CSS file is utilized in an HTML web page, analyzing it within the browser’s developer instruments will present the unique src file and line. For instance, viewing <physique> types will spotlight src/_elements.css line 2 somewhat than types.css line 8.

You may create an exterior supply map by including a --map (or -m) swap to the postcss command. There’s little profit apart from the CSS file is cleaner and the browser doesn’t have to load the supply map except the developer instruments are open.

You may take away the supply map with --no-map. All the time use this feature when outputting CSS recordsdata for manufacturing deployment.

Set up and Use the AutoPrefixer Plugin

The Autoprefixer plugin is usually a developer’s first encounter with PostCSS. It provides vendor prefixes in line with browser utilization and guidelines outlined at caniuse.com. Vendor prefixes are much less utilized in fashionable browsers which cover experimental performance behind flags. Nonetheless, there are nonetheless properties reminiscent of user-select which require -webkit-, -moz-, and -ms- prefixes.

Set up the plugin globally with this:

npm set up -g autoprefixer

Then reference it as one other --use choice in your postcss command:

postcss ./src/foremost.css --use postcss-import --use autoprefixer --output ./types.css

Look at the label declaration from line 11 of types.css to view the vendor-prefixed properties:

label {
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}

AutoPrefixer makes use of the browserlist module to find out which browser prefixes so as to add. The default is:

  • > 0.5%: a browser with a minimum of 0.5% market share
  • final 2 variations: the final two releases of these browsers
  • Firefox ESR: together with Firefox Prolonged Help Releases
  • not lifeless: any browser that’s not discontinued

You may change these defaults by making a .browserslistrc file. For instance:

> 2%

Or you possibly can add a "browserslist" array to package deal.json in a Node.js undertaking. For instance:

"browserslist": [
   "> 2%"
]

Focusing on browsers with a 2% or extra market share solely requires a -webkit- prefix in Safari:

label {
  -webkit-user-select: none;
          user-select: none;
}

Minify CSS with cssnano

cssnano minifies CSS by stripping whitespace, feedback, and different pointless characters. Outcomes will differ, however you possibly can count on a 30% file discount which you’ll deploy to manufacturing servers for higher internet web page efficiency.

Set up cssnano globally:

npm set up -g cssnano

Then add it to your postcss command. We’ll additionally embody --no-map to disable the supply map:

postcss ./src/foremost.css --use postcss-import --use autoprefixer --use cssnano --no-map --output ./types.css

This reduces the CSS file to 97 characters:

*{margin:0;padding:0}physique{font-family:sans-serif}label{-webkit-user-select:none;user-select:none}

Routinely Construct when Supply Recordsdata Change

The PostCSS --watch choice mechanically builds your CSS file when any of the supply recordsdata change. You may additionally wish to add the --verbose swap which experiences when a construct happens:

postcss ./src/foremost.css --use postcss-import --use autoprefixer --use cssnano --no-map --output ./types.css --watch --verbose

Your terminal will present Ready for file adjustments. Make a change to any file and types.css is rebuilt. PostCSS can even report any issues reminiscent of syntax errors.

To complete, press Ctrl | Cmd + C within the terminal.

Create a PostCSS Configuration File

The postcss command will turn into lengthy and cumbersome as you add additional plugins and choices. You may create a JavaScript configuration file which defines all of the choices and may logically decide whether or not it’s operating in a growth or manufacturing atmosphere.

Create a configuration file named postcss.config.cjs within the root of your undertaking folder. Aso word the next:

  • you possibly can put the file in one other folder, however you’ll have to specify --config <dir> when operating postcss
  • you need to use postcss.config.js because the file identify, however PostCSS could fail in Node.js tasks which have "kind": "module" set in package deal.json

Add the next code to postcss.config.cjs:


module.exports = (cfg) => {

  const devMode = (cfg.env === 'growth');

  return {

    map: devMode ? 'inline' : null,
    plugins: [
      require('postcss-import')(),
      require('autoprefixer')(),
      devMode ? null : require('cssnano')()
    ]

  };

};

PostCSS passes a cfg object which comprises the command line choices. For instance:

{
  cwd: '/residence/yourname/cssproject',
  env: undefined,
  choices: {
    map: { inline: true },
    parser: undefined,
    syntax: undefined,
    stringifier: undefined
  },
  file: {
    dirname: '/residence/yourname/cssproject/src',
    basename: 'foremost.css',
    extname: '.css'
  }
}

The module should return an object with non-obligatory properties:

  • map: the supply map setting
  • parser: whether or not to make use of a non-CSS syntax parser (such because the scss plugin)
  • plugins: an array of plugins and configurations to course of within the order specified

The code above detects whether or not the postcss command has an --env choice. This can be a shortcut for setting the NODE_ENV atmosphere variable. To compile CSS in growth mode, run postcss with --env growth and, optionally, set --watch --verbose. This creates an inline supply map and doesn’t minify the output:

postcss ./src/foremost.css --output ./types.css --env growth --watch --verbose

To run in manufacturing mode and compile minified CSS with no supply map, use this:

postcss ./src/foremost.css --output ./types.css

Ideally, you might run these as terminal or npm scripts to lowering typing effort additional.

PostCSS Progress

You now know the fundamentals of PostCSS. Enhancing the performance is a matter of including and configuring additional plugins. Make investments a while and also you’ll quickly have a workflow you possibly can adapt for any internet undertaking.

The tutorial on the best way to use PostCSS as a configurable various to Sass gives extra configuration examples and plugin choices.

Additional hyperlinks:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments