Monday 17 October 2016

Chigboken

Advanced WordPress Development: Using Gulp to Streamline Your Workflow

Advanced WordPress Development: Using Gulp to Streamline Your Workflow


No  matter what languages you’ve used in the past to development websites, you’ve no doubt had to complete menial, monotonous tasks – image optimization, JavaScript minification, concatenation, compiling supersets like SCSS and CoffeeScript to their native counterparts, creating the final build… just to name a few.
Fortunately, build scripts such as Gulp and Grunt can take care of these rather boring tasks for you. All they require is a bit of setup and some command line know-how.
In this tutorial, we’ll focus on how you can make the most of Gulp; how you can delegate common tasks to Gulp so you can concentrate on more important tasks like actually coding.
Note: It’s important that you have a working knowledge of PHP as this is the foundational language of WordPress for this series, which covers advanced topics aimed at developers. I’ll be referring to code snippets throughout this series.

Installing Gulp

Gulp can be installed easily with npm, which is short for Node Package Manager. Node itself is a hugely popular and wonderfully useful JavaScript runtime environment, which includes npm.To get started first install Node using the handy installer on the
To get started, first install Node using the handy installer on the main Node site.
Next, use the code below to install Gulp. That’s it!
npm install --global gulp-cli
install.sh hosted with ❤ by GitHub

A Note About Node and npm Packages

npm is a tool that can be used to install packages like Gulp. Most packages are meant to be installed locally – they will only be available in the folder of the project you add them to.
npm uses a special file named package.json, which contains metadata about your project. It’s name, description, version and – most importantly – the packages that it uses.
As a result, Node projects are very agile. You don’t need to share all the packages used or check them into version control. Just make sure package.json is available and anyone will be able to use the npm install command to get all prerequisites in a few seconds.
Some packages – like Gulp – can be installed globally. This is not a requirement, but it is convenient for tools, especially development tools, that we use all the time.

Installing Packages

We’ll be installing a few packages related to Gulp for this tutorial. The syntax to accomplish this is the following:
npm install --save-dev package1 package2 package3
# alrenative shorthand
npm i -D package1 package2 package3
npm-install.sh hosted with ❤ by GitHub
You can install one or more packages by separating their names with spaces. --save-dev or -D indicates that we’d like to save the packages as development dependencies. They will be placed in the package file for us.

Starting a New Project

For our first example, we’ll create a WordPress theme. You should know how to do that by now: create a new folder in the themes directory, add an index.php and astyle.css file with the appropriate information, etc. We’ll also add a package.jsonfile to store our dependencies.
Let’s set all that up within the terminal:
mkdir example-gulp-theme && cd example-gulp-theme
touch header.php footer.php functions.php index.php style.css
npm init
setup.sh hosted with ❤ by GitHub
Issue these commands one-by-one. Note the && in the first command. This allows me to issue a second command, which means that the first line will create a directory and immediately switch to it as well.
The npm init command is a wizard for the package.json file. It will ask you a series of questions and you can press Enter for each to use the defaults.
Questions following the npm init command
Questions following the npm init command
We’ll need to install Gulp locally as well to make sure we can use it within our project. The following command will take care of it for us:
npm i -D gulp
gulp-install.sh hosted with ❤ by GitHub
When you install your first dependency, you’ll see a new folder named node_modules. This will contain hordes of packages (each one you install will have multiple dependencies of its own). You do not need to add this to your repository; all that is needed is the package file.
The package.json file
The package.json file

Gulp Basics

Gulp is essentially a task runner. You define a condition when a task should run and then define exactly what the task should do. For example: if you run gulp optimize in the command line, Gulp should find all images within your project and optimize them.
Since Gulp is a framework and not a magic solution to everything, you need to tell it what the conditions are and what to do when they are met. You use the gulpfile.jsfile, which contains all the information Gulp needs to perform its tasks.
Let’s create a gulpfile now with minimal information:
var gulp = require('gulp');
gulp.task('default', function() {
// place code for your default task here
});
gulpfile.js hosted with ❤ by GitHub
The first line imports Gulp itself. This is followed by our first task named “default.” When you type gulp into the command line the default task is run. We’ll be adding some code in there later to make some magic happen!
To create a task from start to finish we’ll need to follow a simple checklist:
  1. Find a package that can perform the task,
  2. Install the package,
  3. Add it to the gulpfile, and
  4. Configure the task by setting the conditions and its options.

A quick Google search turned up the gulp-imagemin package, which minifies PNG, GIF and JPG images. Perfect! Installation and usage instructions are usually available on-site. To install this plugin use the following command:
npm i -D gulp-image-optimization
install-image-opt.sh hosted with ❤ by GitHub
To add it to the gulpfile we’ll include it right under our initial inclusion of Gulp itself:
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
gulp.task('default', function() {
// place code for your default task here
});
gulpfile-imageop.js hosted with ❤ by GitHub
Finally, we need to define a condition – when a task is run – and tell Gulp what to do. Here’s the code for a new task named “optimize-images”:
gulp.task('optimize-images', function(cb) {
gulp.src(['./*.png','./*.jpg','./*.gif','./*.jpeg', './images/**/*.*'])
.pipe(imagemin())
.pipe(gulp.dest('./'))
});
optimize-images.js hosted with ❤ by GitHub
Using the src() function, I told Gulp what files to sort through when searching for images. We’re looking for all GIF, JPG, JPEG and PNG files in the root directory and all files in the images directory.
We’re then “piping” the contents of all matched files into a function namedimagemin() which we imported at the top of the file; this is the package we installed earlier. This function will modify the stream and pass it on.
We pipe the received stream to the dest() function which describes the output location for the files. The given value will overwrite the original files with the optimized version.
If you run the gulp optimize-images command in the terminal you should see the following output and find that your image has decreased in size:
Gulp Image Optimization At Work
Gulp Image Optimization At Work

How Gulp Works

I think the example explains it well, but I want to reiterate and add some additional information. The general process behind a gulp task is the following:
  1. Target some source files
  2. Read their content and pass them on to a function
  3. This passing on, or piping, can happen multiple times within a task. Each function takes the result of the previous, modifies it and passes it along.
  4. Take the resulting stream and output it to the designated location
Let’s look at processing SASS files as another example. Here’s how the algorithm above could be applied if we wanted to compile all our sass files, automatically add vendor prefixes and minify the result:
  1. Find all .scss files
  2. Pass their content on to the Sass compiler
  3. Pass the resulting content to the auto prefixer
  4. Pass the result to the minifier
  5. Save the result to the same source file
Let’s make that happen in Gulp. We’ll need three packages:
We can install them in one go using the following command:
npm i -D gulp-sass gulp-autoprefixer gulp-clean-css
install-3.sh hosted with ❤ by GitHub
Next, let’s add them to our gulpfile right at the top
var cleanCSS = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
add-3.js hosted with ❤ by GitHub
We should also add some Sass to our theme. Let’s create a Sass file in the main directory called style.scss with the following content:
/*
Theme Name: Gulp Test Theme
Description: A quick WordPress Gulp example theme
Author: Daniel Pataki
Author URI: http://danielpataki.com
Version: 1.0.0
*/
$bg: #ff9900;
html {
background: $bg;
transition: all 200ms linear;
user-select:none;
}
style.scss hosted with ❤ by GitHub
Finally, we need to create the task which will perform all the actions we need. Here’s the full code with the explanation underneath.
gulp.task('css', function() {
gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest('./'));
})
css-task.js hosted with ❤ by GitHub
I’ve taken all the SCSS files in the root directory, piped them to the sass() function, followed by the autoprefixer, followed by the cleanCSS function and finally I piped everything to the main directory which will result in style.scss being output tostyle.css. The resulting CSS is the following:
html{background:#f90;transition:all .2s linear;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}
style.css hosted with ❤ by GitHub
As you can see, everything has been minified – the variable has been replaced with its value and vendor prefixes have been added where necessary.
To come up with this code I went to the documentation of each and copy-pasted the pipe part of the example, it really as that simple. The commands may have some options worth looking into but most work fine out-of-the-box.

Watching Files

By issuing our commands we’ve already come a long way. We can get Gulp to do whatever we want as long as we find the correct package and add it to our Gulpfile. However, we can do more.
When developing, especially CSS, we tend to save and modify a lot. We would need to issue the gulp css command continuously. Gulp has a great mechanism called watching which allow us to detect changes in files and automatically issue commands. We can build this in on top of everything we’ve done already.
We essentially need to add a new directive: when a file within the specified set changes, run a task.
Get started by installing gulp-watch and adding it to the gulpfile, this should be easy now that you’ve done it a couple of times.
The new task is pretty simple. All we’re doing is setting the files to watch, and if one of them is matched, we perform one of our existing tasks:
gulp.task('watch-css', function () {
gulp.watch('./*.scss', ['css']);
});
watch.js hosted with ❤ by GitHub
When you run this task with gulp watch-css you should see something like the screenshot below in your terminal. Note that it does not exit back to the prompt it just “hangs” there. It is waiting for an indicated file to change. When it does it will add some more output. If you’d like to return to the prompt, press control + C.
Gulp Watch Output
Gulp Watch Output

Overview

That’s all there is to Gulp, a few simple rules to follow when adding a task and you can automate to your heart’s content. You can concatenate files, error check them, copy/move/delete files, and even write your own packages for anything not covered by third party packages.
Tools like Gulp can shave hours of work off your work days, which means they are possibly the most worthwhile additions to your skillset.

Chigboken

About Chigboken -

Author Description here.. Nulla sagittis convallis. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.

Subscribe to this Blog via Email :