Table of Contents for
Mastering PostCSS for Web Design

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering PostCSS for Web Design by Alex Libby Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. Mastering PostCSS for Web Design
  4. Mastering PostCSS for Web Design
  5. Credits
  6. About the Author
  7. About the Reviewer
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Conventions
  13. Reader feedback
  14. Customer support
  15. 1. Introducing PostCSS
  16. Introducing PostCSS
  17. Setting up a development environment
  18. Creating a simple example using PostCSS
  19. Linting code using plugins
  20. Exploring how PostCSS works
  21. Summary
  22. 2. Creating Variables and Mixins
  23. Creating a hover effect example
  24. Transitioning to using PostCSS
  25. Adding variable support to PostCSS
  26. Updating our hover effect demo
  27. Setting the order of plugins
  28. Creating mixins with PostCSS
  29. Looping content with PostCSS
  30. Summary
  31. 3. Nesting Rules
  32. Navigating through pages
  33. Transitioning to using PostCSS plugins
  34. Exploring the pitfalls of nesting
  35. Making the switch to BEM
  36. Exploring our changes in more detail
  37. Summary
  38. 4. Building Media Queries
  39. Exploring custom media queries in PostCSS
  40. Making images responsive
  41. Adding responsive text support
  42. Optimizing media queries
  43. Retrofitting support for older browsers
  44. Moving away from responsive design
  45. Taking things further with CSS4
  46. Summary
  47. 5. Managing Colors, Images, and Fonts
  48. Managing fonts with PostCSS
  49. Creating image sprites
  50. Working with SVG in PostCSS
  51. Adding support for WebP images
  52. Manipulating colors and color palettes
  53. Creating color functions with PostCSS
  54. Summary
  55. 6. Creating Grids
  56. Creating an example with Bourbon Neat
  57. Exploring the grid plugins in PostCSS
  58. Transitioning to using PostCSS-Neat
  59. Creating a site using Neat and PostCSS
  60. Adding responsive capabilities
  61. Summary
  62. 7. Animating Elements
  63. Moving away from jQuery
  64. Making use of pre-built libraries
  65. Switching to using SASS
  66. Making the switch to PostCSS
  67. Exploring plugin options within PostCSS
  68. Updating code to use PostCSS
  69. Creating a demo in PostCSS
  70. Optimizing our animations
  71. Using our own animation plugin
  72. Summary
  73. 8. Creating PostCSS Plugins
  74. Dissecting the architecture of a standard plugin
  75. Creating an transition plugin
  76. Building a custom font plugin
  77. Simplifying the development process
  78. Guidelines for plugin building
  79. Making the plugin available for use
  80. Summary
  81. 9. Working with Shortcuts, Fallbacks, and Packs
  82. Exploring plugin packs for PostCSS
  83. Adding shortcuts with Rucksack
  84. Linting and optimizing your code
  85. Providing fallback support
  86. Summary
  87. 10. Building a Custom Processor
  88. Exploring our processor
  89. Dissecting issues with our processor
  90. Optimizing the output
  91. Adding reload capabilities
  92. Extending our processor further
  93. Testing the final pre-processor
  94. Getting started with some hints and tips
  95. Introducing the CSStyle library
  96. Summary
  97. 11. Manipulating Custom Syntaxes
  98. Preparing our environment
  99. Implementing custom syntax plugins
  100. Parsing CSS
  101. Formatting the output with the API
  102. Highlighting our syntax code
  103. Summary
  104. 12. Mixing Preprocessors
  105. Exploring the conversion process
  106. Introducing the Pleeease library
  107. Compiling with other preprocessors
  108. Using the PreCSS library
  109. Converting a WordPress installation
  110. Setting up our environment
  111. Considering the conversion process
  112. Making changes to our code
  113. Compiling and testing the changes
  114. Summary
  115. 13. Troubleshooting PostCSS Issues
  116. Exploring some common issues
  117. Getting help from others
  118. Summary
  119. 14. Preparing for the Future
  120. Converting CSS4 styles for use
  121. Supporting future syntax with cssnext
  122. Creating plugins to provide extra CSS4 support
  123. Summary
  124. Index

Implementing custom syntax plugins

The PostCSS ecosystem contains over 100 plugins at last count; this is on the increase. These plugins will all serve different needs, but will have one thing in common: the process they use to transform our code.

Now, we should be clear that this similarity is at a very high level; we are not referring to the technical details of each plugin! This aside, when creating our own custom syntax, we must follow a three-step process:

  1. We first put our code through a parser.
  2. We then transform it using anyone of a number of plugins.
  3. We finally stringify it, or convert it to valid CSS in string format.

We already have a handful of plugins that allow us to work with other syntaxes within a PostCSS environment; these include languages such as less or JavaScript:

Name of plugin

Purpose of plugin

sugarss

This plugin is an indent-based syntax like SASS or Stylus.

Plugin is available from https://github.com/postcss/sugarss.

postcss-less

We can use this plugin to transform less into valid CSS. Note: it does not compile code.

Plugin is available from https://github.com/webschik/postcss-less.

postcss-js

Anyone working with JavaScript can use this plugin to write styles in JS or transform React Inline Styles, Radium, or JSS.

Plugin is available from https://github.com/postcss/postcss-js.

postcss-scss

For those of you using SASS, this plugin is perfect for working with SASS code; it does not compile code to CSS.

Plugin is available from https://github.com/postcss/postcss-scss.

postcss-safe-parser

This plugin is perfect for finding and fixing CSS syntax errors.It's available to download from https://github.com/postcss/postcss-safe-parser.

poststylus

We can use this plugin to transform styles created using the Stylus library into valid CSS. Note: it does not compile code.

Plugin is available from https://github.com/seaneking/poststylus.

Although all of these plugins serve a different purpose, they all follow the same principle: they parse the code and transform it, before converting it to a format that can be saved to file as a valid style sheet output.

Leaving aside which parser we use, there is one question though: why would we want to manipulate our code directly? There are a few reasons for needing to alter the code directly; here are a few:

  • We may want to create a report that details facts and figures about our code for reference purposes; it is true that there will be plugins or scripts available to do this already, but PostCSS can get us the basics during compilation, and not as a separate process.
  • How about this for an idea? If you happen to use an application such as Adobe Color CC, then we can consider using the API to directly transform specific colors into valid RGB(A) or HEX equivalent values. We could use a plugin to achieve this, but performing this directly using the API allows us to retain flexibility with our choice of colors.
  • There is nothing stopping us from dissecting existing plugins, and rebasing the tasks they perform into something that we could add to a task runner file, and then adapt to our needs. We might ultimately consider creating a plugin, but if the steps required are very specific to our needs, then a plugin may not be a useful addition.
  • There are occasions when error handling can be lacking. The API contains some useful functionality that allows us to add suitably formatted messages on screen, if our process fails.

These are just a few ideas to get started, in addition to manipulating existing non-PostCSS styles (such as those created using SASS, for example).

Enough talking, I feel a demo coming! We've met some of the plugins available, so it's time to put them to good use; two of particular interest are the postcss-scss and postcss-safe-parser plugins. Let's dive in and take a look at them in more detail, beginning with postcss-safe-parser.

Parsing content and fixing errors

Over the next few pages, we'll touch on using a couple of parser plugins, to show how easy it is to transform our code. We will take a look at a plugin that removes the need for SASS (at least at a basic level); before we do so, let's first explore using the postcss-safe-parser plugin.

The postcss-safe-parser plugin, available from https://github.com/postcss/postcss-safe-parser, is perfect for finding and fixing CSS errors. It's a simple plugin to use and install; let's make a start:

  1. We'll start by installing the plugin, so go ahead, and fire up a Node.js command prompt session, then change the working directory to the root of our project area.
  2. At the prompt, enter this command, then press Enter to install the plugin:
    npm install postcss-safe-parser --save-dev
    
  3. Next, go ahead and extract a copy of the T58 – parsing invalid content folder from the code download that accompanies this book; save it to the root of our project area.
  4. Copy the package.json and gulpfile.js files from it to the root of our project area.
  5. Switch back to the NodeJS command prompt session, then at the prompt, enter gulp and press Enter.

If all is well, we should see a successful compilation: a file marked output.css will be created at the root of our project area.

Go ahead and open it. Even though our example only contained one malformed selector, the file contains the same selector, but this time with the missing closing parenthesis added. We can also see the results appear in the console log at the same time as seen in the following screenshot:

Parsing content and fixing errors

So what's going on here? Well, some of this will be familiar. We're using a standard format task in our Gulp file, along with references to some of the plugins that we've already met, such as autoprefixer.

The content that is of interest to us though, is in the default Gulp task as seen in the following screenshot:

Parsing content and fixing errors

The task may seem a little complex, but in reality, we're parsing our CSS, prior to manipulating it. We start by defining a postcss object (into which feeds a request to run autoprefixer). This then processes our CSS into an AST, using a parser to find and fix any issues, before piping it out on screen and into a file named output.css in our project area.

Note

Abstract Syntax Trees (AST) are a graphical tree representation of the syntactic structure of our CSS style sheets or code.

Okay, our example was very simplistic, but this was intended to show you how the principle works. In this next example, the same principle has been used to convert standard SCSS code to valid CSS; note, though, that we're not calling SASS (as we have done before), but converting the SCSS code to valid CSS styles.

Parsing SCSS content

In our previous demo, we explored the use of PostCSS to parse our CSS and added the missing closing bracket as a fix for our code. It was a simplistic example; perfect if you're working with standard CSS, but what if your projects are using SASS?

Well, as part of our next example, we'll prove that using a compiler is now old hat; we'll use the postcss-scss plugin (from https://github.com/postcss/postcss-scss) to directly transform our SASS code, before unwrapping the nesting styles using the postcss-nested plugin (available from https://github.com/postcss/postcss-nested):

  1. We'll start by installing the postcss-scss plugin. Go ahead and fire up a NodeJS command prompt session, then change the working directory to the root of our project area.
  2. At the prompt, enter this command, then press Enter:
    npm install postcss-scss --save-dev
    

    Keep the session open when the plugin has completed installation:

    Parsing SCSS content
  3. From the downloaded code that accompanies this book, go ahead and extract a copy of the package.json file from the T59 – Parsing SCSS content folder. Save this to the root of our project area.
  4. From the same T59 – Parsing SCSS content folder, copy the contents of the src folder to the src folder at the root of our project area.
  5. In a new file, add the following code and save it as gulpfile.js in the src folder at the root of our project area:
    'use strict';
    var gulp = require('gulp');
    var postcss = require('postcss');
    var fs = require('fs')
    var autoprefixer = require('autoprefixer');
    var nested = require('postcss-nested');
    
    var scss = fs.readFileSync('src/styles.scss', 'utf-8');
    
    gulp.task('default', function () {
      var syntax = require('postcss-scss');
      postcss([ autoprefixer, nested() ]).process(scss, { syntax: syntax }).then(function (result) {
        fs.writeFileSync('dest/styles.css', result.content);
      });
    });

The keen-eyed amongst you will spot the reference to postcss-nested. We cannot call PostCSS without specifying something, so we'll use this plugin to unwrap the nested statements in our code:

  1. Revert back to the NodeJS command prompt session, then add this command and press Enter:
    npm install postcss-nested --save-dev
    
  2. Once Node has completed installing the plugin, enter gulp at the prompt then press Enter:
    Parsing SCSS content
  3. If all is well, we will see a compiled file appear in the dest folder:
    Parsing SCSS content

But hold on a moment: this is a valid CSS file, right? Absolutely. But…we've so far had to use a compiler to produce valid CSS code; how come we haven't needed to add one now?

Exploring what happened

Well, the answer lies in the conversion process—traditionally we would have had to compile our code, even though standard SASS files are a superset of current CSS. Instead, we've simply rewritten our code using a syntax that translates a standard SCSS file to valid CSS.

If we take a look at our Gulp file in more detail, we can see references to the standard gulp-postcss plugin, along with declared instances of the fs, autoprefixer, postcss-nested, and postcss-scss plugins. The key for this demo starts on line 10, where we declare an instance of the scss variable, and use the file system (fs) plugin for Node to read the contents of the file into this variable.

Once into the task, we create an instance of PostCSS as an object, before feeding it the autoprefixer and nested() plugins (as variables). We then process our SASS code using the syntax that comes with the postcss-scss plugin, before piping out the contents as a file into the dest folder in our project area.

See? Nice and easy; not a SASS compiler in sight! This simple change removes the need for any dependency on a compiler, after all, SCSS files are just standard CSS text files, so why use a compiler? With all of this talk of parsing CSS (or SCSS for that matter), it's worth spending some time exploring what we mean by this, and how it is important to the whole process.