Mastering PostCSS for Web Design - Alex Libby - E-Book

Mastering PostCSS for Web Design E-Book

Alex Libby

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Explore the power of PostCSS to write highly performing, modular, and modern CSS code for your web pages

About This Book

  • Incorporate cutting-edge styles in your web pages with PostCSS
  • Simplify the process of writing CSS to a great extent using PostCSS shortcuts, fallbacks, and pack plugins
  • This in-depth, step-by-step guide will help you master PostCSS, to create amazing and responsive web designs

Who This Book Is For

This book is ideal for web developers and designers who are comfortable with HTML5 and CSS and now want to master PostCSS for web design. Web designers who have been using SASS or Less and now want to adopt PostCSS would also find this book useful.

What You Will Learn

  • Add mixin and variable support to PostCSS along with conditional support
  • Explore the different ways of nesting code such as BEM and standard nesting within PostCSS
  • Optimize media queries built with PostCSS to get the best performance
  • Add dynamic styling elements such as images, fonts, grids, and SVG and retina support using existing preprocessors as well as PostCSS
  • Get familiar with using plugins, and extend PostCSS with the API
  • Build a fully working custom preprocessor and test it on different sites such as WordPress
  • Write a custom syntax in PostCSS while still using pre-built syntaxes such as Less, SASS, or Stylus
  • Provide support for future CSS such as CSS4 using current CSS3 classes

In Detail

PostCSS is a tool that has quickly emerged as the future of existing preprocessors such as SASS and Less, mainly because of its power, speed, and ease of use. This comprehensive guide offers in-depth guidance on incorporating cutting-edge styles into your web page and at the same time maintaining the performance and maintainability of your code.

The book will show how you can take advantage of PostCSS to simplify the entire process of stylesheet authoring. It covers various techniques to add dynamic and modern styling features to your web pages. As the book progresses, you will learn how to make CSS code more maintainable by taking advantage of the modular architecture of PostCSS. By the end of this book, you would have mastered the art of adding modern CSS effects to web pages by authoring high performing, maintainable stylesheets.

Style and approach

This comprehensive book provides in-depth guidance on how to build a PostCSS powered responsive site from scratch. Following a step-by-step approach, you will learn how to add modern styles to web pages. It also contains several tips and best practices on how you can optimize your sites by writing high performing code in PostCSS.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 540

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering PostCSS for Web Design
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Introducing PostCSS
Discovering the art of processing
Introducing PostCSS
Exploring the benefits of using PostCSS
Considering some of the pitfalls
Clearing up some misconceptions
Preparing for exercises in this book
Setting up a development environment
Installing PostCSS
Creating a simple example using PostCSS
Adding source map support
Creating minified style sheets
Altering to compile automatically
Linting code using plugins
Exploring how PostCSS works
Making the move from SASS
Summary
2. Creating Variables and Mixins
Introducing variables and mixins
Setting up SASS
Creating a hover effect example
Using Less CSS as an alternative
Transitioning to using PostCSS
Adding variable support to PostCSS
Updating our hover effect demo
Taking it a step further
Setting the order of plugins
Creating mixins with PostCSS
Updating our hover effect demo
Comparing PostCSS to standard processors
Looping content with PostCSS
Iterating through @each statements
Switching to using PostCSS
Summary
3. Nesting Rules
Introducing nesting
Navigating through pages
Preparing our demo
Converting from existing processors
Transitioning to using PostCSS plugins
Converting our demo to PostCSS
Compiling our code
Exploring the pitfalls of nesting
Taking a better approach
Reconsidering our code
Updating our code
Making the switch to BEM
Creating simple message boxes
Compiling and linting our code
Installing BEM support
Exploring our changes in more detail
Fixing our errors
Summary
4. Building Media Queries
Revisiting media queries
Exploring custom media queries in PostCSS
Beginning with plain CSS
Altering our demo to use PostCSS
Making images responsive
Making an image responsive with PostCSS
Implementing responsive capabilities to images
Adding support for retina images
Taking the next steps
Exploring other media possibilities
Adding responsive text support
Optimizing media queries
Retrofitting support for older browsers
Moving away from responsive design
Taking things further with CSS4
Summary
5. Managing Colors, Images, and Fonts
Adding color, fonts, and media to sites
Maintaining asset links
Automating links to assets
Managing fonts with PostCSS
Creating image sprites
Demo – creating a credit card icon bar
Working with SVG in PostCSS
Altering icon images using PostCSS
Exploring the results in more detail
Considering alternative options
Adding support for WebP images
Switching WebP images in and out
Viewing the differences in file sizes
Manipulating colors and color palettes
Displaying and mixing colors using palettes
Dissecting our demo in more detail
Creating color functions with PostCSS
Adjusting colors using functions
Dissecting our demo
Creating colors with PostCSS filters
Exploring our demo in more detail
Comparing with CSS3 filters
Adding Instagram effects to your images
Summary
6. Creating Grids
Introducing grid design
Automating the compilation process
Adding support for Bourbon Neat
Creating an example with Bourbon Neat
Exploring our demo in more detail
Exploring the grid plugins in PostCSS
Transitioning to using PostCSS-Neat
Refining our task list
Testing our configuration
Creating a site using Neat and PostCSS
Making the change to PostCSS
Adding responsive capabilities
Correcting the design
Summary
7. Animating Elements
Revisiting basic animations
Moving away from jQuery
Animating content with Transit.js
Animating with plain JavaScript
Switching classes using jQuery
Making use of pre-built libraries
Dissecting the code for our demo
Switching to using SASS
Creating an animated gallery
Adding the finishing touches
Making the switch to PostCSS
Exploring plugin options within PostCSS
Updating code to use PostCSS
Testing our altered code
Creating a demo in PostCSS
Updating the plugin
Building our demo
Dissecting our demo in more detail
Optimizing our animations
Using our own animation plugin
Exploring the plugin in more detail
Summary
8. Creating PostCSS Plugins
Extending PostCSS with plugins
Dissecting the architecture of a standard plugin
Exploring index.js
Discovering package.json
Exploring test.js
The Vendor module
The List module
Classes available in the API
Nodes available in the API
Methods available in the API
Creating an transition plugin
Creating a test for our plugin
Correcting the errors
Clearing the final error
Performing a test using the plugin
Dissecting our plugin in detail
Building a custom font plugin
Dissecting the functionality of our plugin
Exploring the dangers of publishing this plugin
Simplifying the development process
Guidelines for plugin building
Making the plugin available for use
Summary
9. Working with Shortcuts, Fallbacks, and Packs
Using shortcut plugins in PostCSS
Exploring plugin packs for PostCSS
Writing styles in shorthand
Adding shortcuts with Rucksack
Introducing our demo
Installing Rucksack as a plugin
Easing into using Rucksack
Animating content using the plugin
Dissecting our demo in more detail
Converting our slider to use Rucksack
Dissecting our code
Linting and optimizing your code
Exploring the use of cssnano
Configuring Stylelint as our linter
Providing fallback support
Detecting support for features
Providing support for oldie
Removing style hacks from code
Summary
10. Building a Custom Processor
Creating your processor
Exploring our processor
Dissecting the package.json file
Exploring the Gulp task file
Dissecting issues with our processor
Fixing our Gulp task file
Understanding the changes made
Optimizing the output
Altering our source map support
Taking care of prefixes
Adding support for pseudo-selectors
Updating our code
Dealing with images
Exploring the process
Adding reload capabilities
Extending our processor further
Testing the final pre-processor
Digesting the results of our exercise
Getting started with some hints and tips
Introducing the CSStyle library
Exploring the benefits of using CSStyle
Dissecting our demo
Summary
11. Manipulating Custom Syntaxes
Introducing custom syntaxes
Preparing our environment
Implementing custom syntax plugins
Parsing content and fixing errors
Parsing SCSS content
Exploring what happened
Parsing CSS
Replacing RGBA colors
Exploring how it all works
Formatting the output with the API
Dissecting our example code
Adding source maps
Highlighting our syntax code
Installing themes
Creating a HTML display theme
Summary
12. Mixing Preprocessors
Taking the first steps
Exploring the conversion process
Choosing our plugins
Introducing the Pleeease library
Installing and configuring the Pleeease library
Compiling code manually
Compiling using a task runner
Building an example using Pleeease
Compiling with other preprocessors
Using the PreCSS library
Converting a WordPress installation
Setting up our environment
Considering the conversion process
Making changes to our code
Splitting our style sheet
Adding support for vendor prefixes
Checking our code for consistency
Minifying our code
Creating variables
Adding support for rem units
Nesting rules in our style sheet
Looping through styles
Considering future possible ideas
Compiling and testing the changes
Summary
13. Troubleshooting PostCSS Issues
Fixing some common issues
Exploring some common issues
Not compatible with your operating system…
Task '<name of task>' is not in your gulpfile
Cannot find module '<name of plugin>'
ReferenceError: <name of task> is not defined
Please provide array of postcss processors!
Entries failing to appear in the package.json file
Output of compiling results is not as expected
Getting help from others
Logging issues at Stack Overflow
Finding a bug with PostCSS
Summary
14. Preparing for the Future
Supporting CSS4 styles today
Converting CSS4 styles for use
Validating e-mail addresses
Supporting the new range input
Supporting future syntax with cssnext
Creating a site template with cssnext
Setting up our demo
Creating plugins to provide extra CSS4 support
Adding future color support to CSS
Going back in time
Creating our own plugin
Summary
Index

Mastering PostCSS for Web Design

Mastering PostCSS for Web Design

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2016

Production reference: 1240616

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-589-1

www.packtpub.com

Credits

Author

Alex Libby

Reviewer

Michael Ebbage

Commissioning Editor

Wilson D'souza

Acquisition Editor

Larissa Pinto

Content Development Editor

Riddhi Tuljapurkar

Technical Editors

Chinmay Puranik

Jayesh Sonawane

Copy Editor

Safis Editing

Project Coordinator

Sanchita Mandal

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Production Coordinator

Manu Joseph

Cover Work

Manu Joseph

About the Author

Alex Libby's background is in IT support—he has been involved in supporting end users for almost 20 years in a variety of different environments; a recent change in role now sees Alex working as an MVT test developer for a global distributor based in the UK. Although Alex gets to play with different technologies in his day job, his first true love has always been the open source movement, and in particular, experimenting with CSS/CSS3, jQuery, and HTML5. To date, Alex has written 10 books on subjects such as jQuery, HTML5 video, SASS, and CSS for Packt and has reviewed several more—Mastering PostCSS Web Design is Alex's eleventh book for Packt.

I would like to thank my family and friends for their support throughout the process and the reviewers for their valued comments; this book wouldn't be what it is without them! I would also particularly like to thank Andrey Sitnik for his work in producing PostCSS and being really helpful and patient in answering questions about some of its more complex parts. My grateful thanks also to Ernie Salazar from NPM, who helped with issues with publishing the plugins created for this book, and David Clark for his assistance with getting me back on track with the postcss-bem-linter plugin, also used in the book. Thank you all—I couldn't have finished the book without your help!

About the Reviewer

Michael Ebbage is a software architect who specializes in e-commerce and Java technology-based web applications. He created his first web page almost two decades ago—since then, he's gone on to develop hundreds of websites for some of the UK's biggest companies (many featuring on the FTSE 100 and 250), as the tools and techniques used to do so have continually changed and evolved.

He has a background in software development and holds a BSc (Hons) in computing and information systems. He is also one of the top contributors to Stack Overflow, where you'll regularly find him answering questions on a wide range of web-related languages and technologies.

I'd like to thank the author, Alex, for the opportunity to be involved with this book. It's been a great learning experience, and I now have a renewed admiration for the amount of knowledge and effort that goes into it. I would also like to thank my beloved wife and son for their patience and support during the time I spent working on reviewing it.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

As a developer, I'll bet you have a perfect workflow—you either write styles using plain vanilla CSS or use one of the current processors, such as SASS or Less, to create them. You'll add vendor prefixes using the likes of Autoprefixer—either manually or using a tool, such as Grunt or Gulp.

Sounds familiar? Why would you want to disturb something if it works for you, right?

Trouble is, a friend or colleague has started talking about a new processor by the name of PostCSS—they've piqued your interest sufficiently to want to find out more about what it is and how it works.

Well, welcome to the fast-growing ecosystem that is PostCSS! By itself, the tool doesn't do anything, but when paired with the right plugins (and there are hundreds available for use), it has the potential to become a really powerful processor for you. Gone are the days when we have to depend on a monolithic library such as SASS or less. Instead, we can pick and choose exactly which plugins to use based on our project requirements. PostCSS is an immensely quick processor to use; the question is, are you ready for the ride?

Here's hoping the answer is yes; if so, let's make a start.

What this book covers

Chapter 1, Introducing PostCSS, kicks off our journey with an introduction to the world of PostCSS, exploring its features and how we can use this ecosystem to transform basic code into valid CSS styles that we can use within our projects. You will discover the benefits of using this ecosystem and how its architecture and modular approach allows us to put together a processor that is tailored specifically for our needs.

Chapter 2, Creating Variables and Mixins, takes a look at some of the basic concepts that are familiar to users of existing processor technologies, such as variables and mixins. You will learn how to transition them to PostCSS and discover how the benefits of using these techniques can transition through to using PostCSS.

Chapter 3, Nesting Rules, explores how existing processors, such as SASS or less, take advantage of concepts such as nesting to reduce the amount of code we need to write and how we can replicate the same functionality within our PostCSS processor.

Chapter 4, Building Media Queries, walks us through the basics of adding responsive support to websites using PostCSS and media queries. You'll learn how to retrofit support for older websites and browsers, and explore how we can take things further with the advent of CSS4 media queries and provide support today within PostCSS.

Chapter 5, Managing Colors, Images, and Fonts, examines the plugins available for handling and manipulating images, colors, and fonts within PostCSS. We will work through a number of examples to illustrate how both images and colors can be manipulated within PostCSS, such as creating image sprites or altering colors using palettes within the system.

Chapter 6, Creating Grids, takes us on a journey through constructing the skeleton of a website using grids—we will explore the basic concept behind using grids and discover some of the plugin options available for creating them within PostCSS. We will work through some examples using the Bourbon Neat grid system, before replicating the examples with PostCSS-equivalent plugins and adding responsive capabilities to the resulting code.

Chapter 7, Animating Elements, begins with a quick recap of using JavaScript to animate content, before switching to using CSS for animation, and how you can transition through to using PostCSS. We will explore using some of the more well-known libraries, such as Animate.css, before creating a quick demo using PostCSS and learning how to optimize our animations using PostCSS.

Chapter 8, Creating PostCSS Plugins, teaches us how plugins can be used to extend PostCSS, and takes us through a journey of exploring the typical architecture of such a plugin. You will then take a look at some example plugins before working through creating your own plugins using the boilerplate code available and before testing and making the plugins available for download by users from the Internet.

Chapter 9, Working with Shortcuts, Fallbacks, and Packs, starts by examining some of the shortcut plugins and packs available before exploring how we can supplement them with creating our own shortcut plugins. You will also discover how you can lint and optimize your code using one of the plugin packs available for PostCSS and learn how to provide fall-backs to PostCSS code to help maintain support for older browsers.

Chapter 10, Building a Custom Processor, pulls together some of the techniques we've covered thus far in the book to produce a custom processor that we can use as a basis for transforming code in our projects. You will explore how to optimize the output before adding source map and vendor prefix support and then testing it on a website. You will then round off the chapter with a look at extending the processor to use the CSStyle framework to allow you to write code that works for both SASS or PostCSS.

Chapter 11, Manipulating Custom Syntaxes, introduces us to writing custom syntaxes using the API and explores some of the options available for parsing code written using syntaxes such as SASS or less. We work though some examples of parsing code using PostCSS before converting the output into something that can be displayed on screen or saved to a file. We will also add in support for highlighting our code using the midas library.

Chapter 12, Mixing Preprocessors, shows us how we can begin to mix processors as an aid to make the transition to using PostCSS. We will take a look at the Pleeease library before installing it and using some of its features. We will then set up a compilation process before using it to make changes to a standard WordPress theme.

Chapter 13, Troubleshooting PostCSS Issues, takes a look at some of the more common issues we might experience when using PostCSS, such as the "taskname not in our gulpfile" error. We will also take a look at what to do next if all else fails. We will cover the methods for getting help with an issue or logging details of a bug within either the core PostCSS system or one of its plugins.

Chapter 14, Preparing for the Future, covers some of the possible options for supporting future style standards from what people know as CSS4. You will also explore some of the risks involved and how you can replicate support using existing plugins available today or extend them to increase support for new CSS4 selectors.

What you need for this book

All you need to work through most of the examples in this book is a simple text or code editor, a copy of NodeJS (for your platform), Internet access, and a browser. I recommend installing Sublime Text 3; it works well with Node and Gulp, which we will use throughout the book.

Some of the examples make use of additional plugins; most (if not all) can be installed directly from within NodeJS. Details are included within the appropriate chapter along with links to view the plugin source code and documentation.

Who this book is for

The book is for frontend developers who are familiar with HTML5 and CSS3, but want to master PostCSS as part of simplifying their development workflow or remove the dependency on existing processors, such as SASS or Stylus. To get the most out of this book, you should have a good knowledge of HTML, CSS3, and JavaScript, and ideally, have some experience of using preprocessors such as SASS, Less, or Stylus.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-PostCSS-for-Web-Design. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/MasteringPostCSSForWebDesign_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Introducing PostCSS

A key part of any website is styling—it doesn't matter if this is for a simple element tag or a complex animation; a website is not a website without color and action. Building styles for any online presence takes time and effort—we can reduce development time by using a preprocessor to automate the creation of styles, automatically apply vendor prefixes and the like, but the extra dependency of a library can be like using a sledgehammer to crack a nut!

Enter PostCSS—its unique modular style allows us to create a leaner, faster CSS processor, with no external dependencies. In this chapter, we look at installing PostCSS, understanding its architecture, and learn how to use its speed and power to compile code into valid CSS. We will cover a number of topics throughout this chapter, which will include the following:

Considering the benefits of creating our own preprocessorIntroducing PostCSS and exploring its featuresSetting up a development environment using PostCSSCreating a simple example using PostCSSExploring how PostCSS works and its architecture

Let's make a start…!

Note

All of the exercises in this book are written for the Windows platform; please adjust accordingly if you use a different operating system.

Discovering the art of processing

A question: what do SASS, Stylus, Haml, and Less all have in common?

The answer is, they are all compilers, source to source compiling, or transpilers (to give them their official name), that have been around since the 1980s. They have appeared in many different formats, with Digital Research's XLT86 being one of the earliest versions, dating from 1981.

More recently, the well-known SASS processor arrived in 2006; this was followed by Less, created by Alexis Sellier in 2009. Both work in a similar fashion: they take a set of rules and compile it into valid CSS. We can extend CSS with all manner of features, such as variables, mixins, functions, and more. Although processors may not help cut down the physical number of lines we have to write, they help us reorganize code into more manageable blocks that we can reuse in future projects, which helps make CSS easier to maintain.

But, as is nearly always the case, there are some drawbacks to using processors:

There is nearly always a dependency involved, in some form or other—with SASS, it's Ruby; if you're using Less, it's a library, even though it is written in JavaScriptOur project may only use a small amount of preprocessed code, yet we are forced to rely on what can be a large library, such as SASSProcessing style sheets using a preprocessor is slow; it may only be a few seconds, but this builds up over time to become a significant amount of time spent waiting for processes to complete

Hmm, this doesn't make processing so attractive! But what if there were a way to alleviate all of these issues, and remove the need for dependencies at the same time?

Well, there is: let's build our own processor! Okay, this might sound a little crazy, but as someone once said, there is method in this madness, so bear with me while I explain why this may be a better option.

Introducing PostCSS

At the beginning of this chapter, I mentioned that we would focus on creating our own preprocessor, right? Well, I have a little confession to make: we're not. Hold on, what gives?

Well, we will create a preprocessor…but we will also create a postprocessor too. Let me explain why—our alternative "option" allows us to create both at the same time. Our alternative option is PostCSS, which can be downloaded from https://github.com/postcss/postcss. PostCSS is used by some major companies, such as Twitter, Google, Bootstrap and CodePen, and even WordPress (in a limited capacity).

PostCSS was built as a Node.js module, so will work with any number of the existing plugins already available for Node.js—we will be using a number of these plugins throughout the book. Let's take a moment to explore some of the benefits of this tool.

Exploring the benefits of using PostCSS

What do we mean by PostCSS? In a nutshell, it can be used to refer to one of two things—the PostCSS core tool or the plugin ecosystem that is powered by the tool. On its own, it doesn't actually do a lot; once we start adding plugins, we can achieve a great deal. Let's explore what this means in practice:

Its modular architecture means we can pick and choose what we use; this allows us to keep the size of the library very small and responsive.Existing processors tend to fall into one of two camps—pre- or post-processing—which is a limiting factor when choosing which to use. PostCSS allows us to perform both operations within the same process, meaning we get the benefits of both worlds of processing!PostCSS comes with seamless support for all of the common task runners such as Gulp, Grunt, or Broccoli; we can combine it with a number of other tasks that can be automated.There are no dependencies for compiling, PostCSS is written entirely in JavaScript, so no need for Ruby, or libraries such as libsass, in order to compile code. The only dependency (as such) is Node.js—many developers will likely already have this installed.There is no need to learn any new languages; every developer will be familiar with JavaScript, and use it in their development process.We can change any plugin in use for something else when needed; we do not get this choice when using a larger library.Its relatively low barrier of entry means we can create any plugins we need very easily, or potentially modify existing ones to better suit our needs.PostCSS is quick—in a test using the postcss-benchmark plugin (available from https://github.com/postcss/benchmark), which contained parsed code, nested rules, mixins, variables, and math, PostCSS came out a clear winner:Perfect—no need to continually update SASS, or have to download a new version of the libsass library, right?

Considering some of the pitfalls

Well, there are some considerations to using a custom processor; the key thing to remember is that PostCSS is neither a pre- nor post-processor, but more of a Swiss Army Knife of a toolbox that we can use to process our CSS code. Let's take a look at some of these drawbacks:

Although we don't need to learn a new language in order to use PostCSS, creating a custom processor will add a layer of complexity to our development process.Its flexible approach means some may treat PostCSS as either a preprocessor or a postprocessor; this short-sighted approach means that you will miss opportunities, so it is crucial to keep an open mind in terms of what PostCSS can offer your development process.Converting code from an existing preprocessor to using PostCSS can be painful; this process only works if we don't try to convert explicitly, but use it as a basis for progressively moving to using PostCSS.PostCSS requires syntactically correct CSS from the start; although we could use any syntax (as PostCSS files are just plain text), compilation can easily fail, even through use of a single line comment!The real benefit of using PostCSS, though, is in its seamless integration into tools such as Gulp—imagine this scenario if you will:

You already develop sites using a preprocessor such as SASS. You can compile code using a standalone processor, but normally prefer to use Node.js and Gulp to complete the task. Sound about right? What about making the move to using PostCSS?

No problem, we can include a section for processing CSS files using PostCSS. The key here is to not use PostCSS to perform the initial compilation, but to perform the post-processing, such as adding vendor prefixes or minifying the results. Once this is established, we can start to incorporate some of the plugins available for PostCSS that allow us to replicate functionality, such as from within SASS. Once we've adjusted existing code to use the format required by the plugins, we can then switch to using PostCSS, and begin to remove our dependency on using SASS.

Clearing up some misconceptions

At this point, it is worth spending a few minutes to help clear up some common misconceptions about PostCSS, although many associate it as being a preprocessor, or even a postprocessor, this isn't what was intended:

Classing PostCSS as a postprocessor, as opposed to a preprocessor (such as Less or SASS) is misguided; PostCSS is capable of compiling in a variety of different use-case scenarios, working on code compiled using any preprocessor, or just plain CSS.PostCSS should not be classed as a tool that should be tied in to any one process (such as writing SASS-based loops or conditionals). There are plugins available to do both, but this is just a small part of the role that PostCSS can play in your development workflow.If you find yourself in a position where "PostCSS" doesn't appear to perform as expected, it is unlikely to be PostCSS itself, but more likely to be a plugin being used that is causing the issue. Although PostCSS is still relatively young, there are plenty of plugins available, so it is worth trying alternatives if you can as a first port of call.

Okay, let's move on, I think it's time for less chat and more action, right? Let's get stuck in to producing something; there's no better time than now to get PostCSS installed and ready for use.

Preparing for exercises in this book

Before we do so, we just need to cover a couple of requirements. First, we need to set up a local web server. It's not critical, but gives a better effect. I personally use WAMP Server (for PC, from http://www.wampserver.com/en), otherwise, Mac users can try MAMP (http://www.mamp.info/en), or the cross-platform Apache web server (from http://www.apachefriends.org). In each case, default settings should be sufficient.

The second requirement is to set up a project area; assuming you have set up a WAMP as a local web server, go ahead and set up a folder called postcss in c:\wamp\www, as shown in this screenshot:

Right, with that out of the way, let's make a start on getting PostCSS installed!

Setting up a development environment

The first step on our journey is to get PostCSS installed—this runs from Node.js; we can use any one of several task runner plugins to install it. For the purpose of the exercises throughout this book, we will use Gulp; if you prefer, alternatives such as Grunt or Broccoli can be used.

Note

When using Node.js, make sure you use the Node.js command prompt, and not node.exe; the exercises will not work when using the latter!

Let's make a start with installing Node and Gulp:

We first need to install Node.js; this is available at http://nodejs.org. Make sure you select the right version that is appropriate for your platform:

When installing, accept all defaults; this will be sufficient for the exercises throughout this book.

Next, bring up a Node.js command prompt, enter the following command, and press Enter:
node –v

The output shown is the version of Node that is installed; this is a quick check to ensure Node.js has indeed been installed correctly:

Now that Node is installed, we need to create a package.json file to store our dependencies for projects. Run this command at the command prompt, and press Enter:
npm init
Node will prompt for information when creating the package.json file; enter the details as shown in the screenshot, or press Enter to accept the given default (shown in brackets, after each question):

We now have Node configured and an empty package.json file in place, so let's add our dependencies. We will start by adding Gulp first:

Revert back to the Node.js command prompt (or bring up a new one if you closed off the previous session).Go ahead and change the working directory to c:\wamp\www\postcss.At the command prompt, enter the following command, then press Enter. This installs Gulp globally and makes it available for use:
npm install --global gulp
Once done, we need to install Gulp for use in our project area—go ahead and run this command, which will add an entry to the package.json file we created earlier in step 3 and step 4:
npm install --save-dev gulp

Once completed, Gulp is now ready for use; we can go ahead and install PostCSS.

Note

A small point on the use of --save-dev: this installs any dependencies required to develop using a specific plugin; if we simply need the dependencies for running the plugin (in a production environment), then we can simply use --save instead.

Installing PostCSS

We're at the interesting stage now—installing PostCSS. PostCSS is available from https://github.com/postcss/postcss, and can be installed into Node using a Gulp plugin. Let's do that now:

We'll start by reverting back to the Node.js command prompt session we've just used (or a new one, if the previous one is closed).At the prompt, go ahead and enter this command, then press Enter:
npm install --save-dev gulp-postcss

If all is well, we should see something akin to this screenshot:

On its own, PostCSS doesn't do anything; to make it more useful, we are going to install three plugins. We will explore using plugins in greater detail later in the book, but for now, don't worry too much about what is happening:

Enter these commands one by one on the Node.js command prompt, pressing Enter after each one:
npm install --save-dev autoprefixer
Let's check our package.json file; if all is well, we should see something akin to this screenshot:

Tip

To make it easier to view JSON files in Sublime Text, try installing and activating a custom theme, such as MonokaiJSON Plus, available to install from https://github.com/ColibriApps/MonokaiJsonPlus.

PostCSS is now installed for use, but if we try to use it, we probably won't get very far, as it needs to be configured for use! Let's take a look at doing that now, by creating a simple example that will add vendor prefixes to some sample CSS rules, and automatically minify the results.

Exploring how PostCSS works

So far, we've covered the basics of setting up and using PostCSS. It's worth taking a moment to learn about how it works, to better understand how we can use it and develop our own plugins for the platform.

PostCSS is like me on a Saturday morning after a good night out: it does nothing! Yes, it's true, by itself, the application doesn't do anything at all; it's when we add plugins into the mix that it starts to become useful.

The key to PostCSS is treating it as an enabler, it is not meant as a direct replacement for your existing preprocessor, or even postprocessor, but to complement them. It works on the basis of parsing code, processing it with any assigned plugins, and rendering the results:

It works by parsing content into an Abstract Syntax Tree (or AST) with a series of nodes. Each node in the tree contains a symbolic representation of an element in your code. In other words, if you had a condition statement that pointed to three possible outcomes, then the AST would have a single node, with three branches representing the possible outcomes.

Note

For an example of an AST, take a look at http://jointjs.com/demos/javascript-ast, which shows the breakdown of a simple arithmetic function using plain JavaScript.

Our AST is then sent through one or more plugins (we must always use one plugin, but can have many in our gulp file). It then converts the code to a long string, before processing it through any assigned plugins and spitting out the result in the form of valid CSS. We can use this as a basis for creating our own plugins, using the boilerplate code and API that are both available from the main PostCSS site on GitHub.

The trick to the plugin stage is in the mix of plugins we must use to satisfy our needs; the better ones should only perform one role. Any that perform multiple tasks are less ideal, as they are likely to contain excess functionality that we don't need in our projects.

Making the move from SASS

Assuming we decided to use PostCSS, there is almost always one question at the top of everyone's mind: how do we make the move?

In short, the key here is not to simply assume existing code can be put through the PostCSS process, as it will likely not work. Instead, we should take an iterative process, and begin to convert low-hanging fruit to using PostCSS. The process will of course require some work, but there are tips on how we can reduce the pain involved in making the switch to PostCSS.

The key to making the transfer is to work out what functionality needs to be processed, then to create the initial framework for a build process (for example, a Gulp or Grunt task file), then to gradually add in plugin support one by one, until you have a fully working compiler.

We can take this a step further, and use plugins that replicate SASS code format into PostCSS; an ideal plugin to start with is Autoprefixer, followed by plugins such as postcss-mixins or postcss-partial-import. We will explore using SASS as a basis for a custom syntax in Chapter 11, Manipulating Custom Syntaxes, where we will use these two plugins, and more, to help make the transition process easier and help remove the dependencies on preprocessors such as SASS or Less. Oh, and above all, being based on JavaScript makes it portable; what more could a developer ask for, I wonder?

Note

Many of the SASS format plugins for PostCSS now come in the PreCSS pack. We will explore using this in Chapter 10, Building a Custom Preprocessor.

Okay, on we go. Over the course of the next few chapters, we will take a look at different processor elements that are commonly used to create build processors, such as variables or mixins. We'll see how they might typically be written in processors such as SASS or Less, then work on converting our code to use PostCSS equivalents before processing to produce valid CSS. We will then finish up with pulling everything together to build your own custom processor for use in future projects.

Summary

Writing valid CSS is an art that has been present since the dawn of the Internet; this takes skill, patience, and time to produce and perfect any masterpiece. Processors such as SASS or Less have helped to make the process more efficient, but are not without their drawbacks; PostCSS allows for a more customized approach, but without the extra baggage. We've covered a few key points around PostCSS throughout this chapter, so let's take a moment to review what we've learned.

We began with a brief look at the art of processing, before introducing PostCSS as a tool. We then explored some of the benefits and drawbacks of using it, and how it can fit in seamlessly with your existing development workflow, with a little careful planning.

Next up, we covered the installation of PostCSS along with Gulp as the task runner/host process, before embarking on a simple demo to introduce how the compilation process works, and that with the right choice of plugins, we can take out some of the manual grunt work required to manage our code (pun intended!). With our code compiling, we then turned our attention to adding a watch facility, and automatic support for linting our code, to ensure we maintain consistent standards.

We then rounded out the chapter with a look at how PostCSS works, and understanding something of its architecture, so that we can begin to make the move from using plain CSS or an existing preprocessor, to using PostCSS.

Phew, we've certainly covered a lot; it's time to really get stuck in now, and start to use PostCSS in earnest. Over the next few chapters, we will explore a number of different concepts that are common to existing preprocessors, and explore how we can benefit from making the transition to using PostCSS. We have to start somewhere, so we'll kick off with using variables, functions, and mixins in the next chapter, and see how we can use some of the techniques from processors, but without the associated baggage!

Chapter 2. Creating Variables and Mixins

A question: how often have you created components such as buttons, where you've used very similar colors multiple times throughout your code? It's a real pain to manually alter. Using a preprocessor such as SASS or Less makes it easier, but with the overhead of a full-sized library.

Can we do it differently? Absolutely; throughout the next few chapters, we'll explore different elements of PostCSS, before pulling it all together to produce a preprocessor application later in the book. We'll begin our journey with a look at using variables and mixins; we'll explore the basics of creating them first, before transitioning to support using PostCSS. In this chapter, we'll cover the following topics:

An overview of creating variables and mixins using existing preprocessorsTransitioning to using PostCSS equivalentsAdding mixin support to PostCSSExamining the differences between standard preprocessors and PostCSS

Let's get cracking!

Introducing variables and mixins

So far, we've covered the basics of installing and configuring PostCSS—although there are a few steps involved, it's an easy process to get started with using the processor. To really get to know it though, there is no substitute for using it in anger; it's amazing how much you can automate, with just a little care and planning!

Let's put that to the test and use it to create a couple of simple examples using variables, functions, and mixins. We'll start with creating the original version using SASS, before converting it to use PostCSS plugins. The demos do assume a level of prior knowledge around using SASS, so if you are at all unfamiliar, then you may like to refer to my book,