Modern WordPress Theme Development With Gulp.js – A Guide

Modern WordPress Theme Development With Gulp.js – A Guide, Packet Json File, Gulp Wordpress

WordPress Theme development is possible with just a text editor and graphics package, but modern toolsets can revolutionize your workflow. In this tutorial, we’ll use Gulp for our WordPress development (Gulp WordPress) to run tasks including:

  • copying newer PHP theme files
  • optimizing images
  • compiling Sass SCSS files into a single, minified CSS file
  • merging ordered JavaScript files, removing debugging statements, and minifying
  • automatically refreshing the browser when files are updated.

What is Gulp, and how can it be used to automate tasks in WordPress?

As they say:

Gulp is a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something.

This perfectly describes what the Gulp really is. Install it in a few easy steps:

  1. Install Node.js.
  2. Install Gulp globally: npm install gulp-cli -g
  3. Make a theme folder with: mkdir themeName and enter the folder withcd themeName.
  4. Initialize your project with npm: npm init

#1 Setup Dependencies (Gulp WordPress)

You will need a fresh WordPress installation for your local development.

Navigate to the theme folder (~/themename/), and run the following npmcommand to install Gulp and all plug-ins as development dependencies:

npm install --save-dev autoprefixer browser-sync css-mqpacker cssnano gulp gulp-concat gulp-deporder gulp-imagemin gulp-newer gulp-postcss gulp-sass gulp-strip-debug gulp-uglify gulp-util postcss-assets

This will create node_modules a folder, that contains the module code and dependencies. For Git users, add node_modules to your .gitignore file.

#2 Adding a Package JSON File

Managing your project dependencies and scripts is made easier with a package.json file. This file not only lists all the packages your project depends on but also allows you to define custom scripts to automate common tasks.
To create a package.json file, navigate to your theme folder and run:

```bash
 npm init 

Follow the prompts to fill in your project details. Once completed, the package.json file will be generated.

Why Package.json is Important?

The package.json file serves several purposes:

  • Dependency Tracking: It lists all the packages your project depends on. This makes it easy for others to understand and recreate your project’s environment.
  • Version Control: Storing dependency information  package.json helps ensure that all contributors use the same package versions. This prevents version conflicts.
  • Scripts: You can define custom scripts that automate various tasks. This is particularly useful for building processes, testing, and running your application.
  • Easy Setup: When you share your project, others can simply run npm install to install all the required packages listed in the package. json.

Updating the npm Command

Now that you have a package.json file, you can update the npm command to install Gulp and its plugins as development dependencies. Run the following command:

npm install

This will read the dependencies from your package.json file and install them automatically. The –save-dev flag is no longer needed, as dependencies are managed through the package.json file.

Hands of a man in a checkered shirt and a ring typing code on a keyboard

#3 Gulp Configuration File

Create a new gulpfile.js the configuration file in your WordPress theme folder. This code should get you started:

// Gulp.js configuration
'use strict';
const

  // source and build folders
  dir = {
    src         : 'src/',
    build       : '/var/www/wp-content/themes/themename/'
  },

  // Gulp and plugins
  gulp          = require('gulp'),
  gutil         = require('gulp-util'),
  newer         = require('gulp-newer'),
  imagemin      = require('gulp-imagemin'),
  sass          = require('gulp-sass'),
  postcss       = require('gulp-postcss'),
  deporder      = require('gulp-deporder'),
  concat        = require('gulp-concat'),
  stripdebug    = require('gulp-strip-debug'),
  uglify        = require('gulp-uglify')
;
// Browser-sync
var browsersync = false;
// PHP settings
const php = {
  src           : dir.src + 'template/**/*.php',
  build         : dir.build
};
// copy PHP files
gulp.task('php', () => {
  return gulp.src(php.src)
    .pipe(newer(php.build))
    .pipe(gulp.dest(php.build));
});

We’re defining our folder location, loading modules, and then creating a PHP task to copy new and updated files to the theme folder. The task has been kept intentionally simple: copy the PHP source files as-is. Later, you can add moreGulpp plugins like PHP Lint.

Save gulpfile.js and create a few .php files in the source template folder. Then enter the following command:

gulp php

All the files will be copied to the theme folder (/var/www/wp-content/themes/themeName/).

#4 Image Processing

Image files can often be compressed further using tools such as imagemin. Add the following code to gulpfile.js:

// image settings
const images = {
  src         : dir.src + 'images/**/*',
  build       : dir.build + 'images/'
};
// image processing
gulp.task('images', () => {
  return gulp.src(images.src)
    .pipe(newer(images.build))
    .pipe(imagemin())
    .pipe(gulp.dest(images.build));
});

Save then run gulp images. Compressed versions of any new or updated images in the source images folder are copied to /var/www/wp-content/themes/themeName/images/.

#5 Sass Compilation

CSS on its own can be fun, but stylesheets are getting larger, more complex, and harder to maintain. This is where a preprocessor can help. Sass lets you use features that don’t exist in style CSS yet, like variables, nesting, mixins, inheritance, and other nifty goodies that make writing style CSS fun again.

WordPress cannot use SASS files directly.

You must compile it in a single style.css file. Add the following code to gulpfile.js:

// CSS settings
var css = {
  src         : dir.src + 'scss/style.scss',
  watch       : dir.src + 'scss/**/*',
  build       : dir.build,
  sassOpts: {
    outputStyle     : 'nested',
    imagePath       : images.build,
    precision       : 3,
    errLogToConsole : true
  },
  processors: [
    require('postcss-assets')({
      loadPaths: ['images/'],
      basePath: dir.build,
      baseUrl: '/wp-content/themes/wptheme/'
    }),
    require('autoprefixer')({
      browsers: ['last 2 versions', '> 2%']
    }),
    require('css-mqpacker'),
    require('cssnano')
  ]
};
// CSS processing
gulp.task('css', ['images'], () => {
  return gulp.src(css.src)
    .pipe(sass(css.sassOpts))
    .pipe(postcss(css.processors))
    .pipe(gulp.dest(css.build))
    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});

Launch this new task with gulp css to:

  • Run the Gulp images task first because images may be required in your CSS.
  • Compile the Sass code in the source scss/style.scss file using the fast LibSass compiler
  • Use PostCSS to automatically add asset references, apply vendor prefixes, pack media queries together, and minify the resulting CSS code.
  • Output the stylesheet to /var/www/wp-content/themes/themeName/style.css.
  • Force a Browsersync CSS to reload (more about that later).

The source scss/style.scssfile must include the WordPress theme metadata at the top, e.g.

 

/*!
    Theme Name: My Theme
    Theme URI: http://www.sitepoint.com/
    Description: Demonstration theme
    Version: 1.0.0
    Author: Craig Buckler (@craigbuckler)
    Author URI: http://www.sitepoint.com/
    Tags: Gulp

    License: MIT
    License URI: http://opensource.org/licenses/mit-license.php
*/

@import '_base';
@import '_forms';
@import '_tables';
@import 'components/_widget1';
// etc...

It is important to use /*! as the first line. This ensures the cssnano minifier does not remove the comment and render your theme unusable.

The postcss-assets plugin allows you to refer to image assets using code such as:

.widget1 {
  width: width('myimage.jpg');
  height: height('myimage.jpg');
  background-image: resolve('myimage.jpg');
}

You can also inline images with automatic Base64 encoding:

.widget2 {
  background-image: inline('myimage.jpg');
}
>?

 

A woman with a ponytail typing code on a laptop with kitchen in the background

#6 JavaScript Processing

Add the following code to gulpfile.js:

// JavaScript settings
const js = {
  src         : dir.src + 'js/**/*',
  build       : dir.build + 'js/',
  filename    : 'scripts.js'
};
// JavaScript processing
gulp.task('js', () => {

  return gulp.src(js.src)
    .pipe(deporder())
    .pipe(concat(js.filename))
    .pipe(stripdebug())
    .pipe(uglify())
    .pipe(gulp.dest(js.build))
    .pipe(browsersync ? browsersync.reload({ stream: true }) : gutil.noop());
});

Run this new task with gulp js to:

  • Process all JavaScript files in the source JS folder.
  • Order the files appropriately. Add comments at the top of your JavaScript files to declare dependencies, e.g., // requires: lib1.js or // requires: config.js lib1.js.
  • concatenate into a single file
  • strip all debugging and console logging statements.
  • Minify the code.
  • Output the resulting code to /var/www/wp-content/themes/themeName/js/scripts.js.
  • force a Browsersync CSS to reload (more about that later).

#7 Run All Tasks

Rather than calling each task separately, we can add the following code to gulpfile.js:

// run all tasks
gulp.task('build', ['php', 'css', 'js']);

You can now use gulp build it to run the JS CSS, and image tasks in parallel. (Note that images this is a dependency of the CSS task, as we set it up early,  so we need not call it directly.)

#8 Enable File Watching and Browsersync

Your workflow can be radically improved by:

  1. Letting Gulp watch for file changes before launching the appropriate task.
  2. Automatically reloading Style CSS and JavaScript files when they change (without a page refresh).
  3. Automatically refreshing the page when a template file changes.

First, we need to define a browsersync task in gulpfile.js. This will create a proxy server for your web server running WordPress on localhost (Change this domain or use an IP address as necessary.):

// Browsersync options
const syncOpts = {
  proxy       : 'localhost',
  files       : dir.build + '**/*',
  open        : false,
  notify      : false,
  ghostMode   : false,
  ui: {
    port: 8001
  }
};
// browser-sync
gulp.task('browsersync', () => {
  if (browsersync === false) {
    browsersync = require('browser-sync').create();
    browsersync.init(syncOpts);
  }
});

Now add a watch task to run Browsersync, watch for file changes, and run the appropriate task:

// watch for file changes
gulp.task('watch', ['browsersync'], () => {

  // page changes
  gulp.watch(php.src, ['php'], browsersync ? browsersync.reload : {});

  // image changes
  gulp.watch(images.src, ['images']);

    // CSS changes
  gulp.watch(css.watch, ['css']);

  // JavaScript main changes
  gulp.watch(js.src, ['js']);
});

Finally, add a default Gulp task that runs an initial build and starts the watch task:

// default task
gulp.task('default', ['build', 'watch']);

Now run gulp from the command line. The console will display output which includes lines similar to:

[BS] Proxying: http://localhost
[BS] Access URLs:
 -------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.99:3000
 -------------------------------------
          UI: http://localhost:8001
 UI External: http://192.168.1.99:8001
 -------------------------------------
[BS] Watching files...

Rather than loading your development site from http://localhost/Enter the address http://localhost:3000/ or the external URL if you are viewing from another device. Your WordPress site will load as before, but Gulp will watch for changes and apply the updates immediately. You’ll never need to switch to your browser and click refresh again!

Hit Ctrl/Cmd + C when you want to stop Gulp (WordPress) processing.

Conclusion

In the ever-evolving landscape of web development, embracing tools like Gulp.js can be a game-changer, especially when it comes to the intricate world of WordPress sites and theme development. Gulp.js goes beyond being just another tool; it becomes a powerful ally that streamlines your work process, fosters collaboration, and elevates the quality of your output.

One of the most compelling aspects of Gulp.js is its ability to significantly enhance the efficiency of working on a WordPress site. WordPress development often involves a multitude of tasks that, while crucial, can be repetitive and time-consuming. Tasks like copying PHP theme files, optimizing images, managing stylesheets, and processing JavaScript can consume valuable time and energy. Gulp steps in as a reliable automation tool, turning these once-manual chores into swift, automated actions.

Imagine the scenario: You’re creating a modern WordPress theme with dynamic styles, intricate JavaScript functionality, and responsive design. Gulp.js becomes your silent assistant that consistently optimizes images for faster loading times, compiles your Sass styles into a well-structured and maintainable CSS file, and carefully organizes your JavaScript into a streamlined and minified script. With each code modification, Gulp.js and its accompanying tasks ensure that your changes are applied instantaneously, seamlessly integrating your updates without the need for manual browser refreshes.

In the realm of a modern WordPress theme, Gulp.js amplifies your capabilities by:

Improving Developer Experience

Gulp.js enhances your development environment, allowing you to focus on creative problem-solving rather than mundane tasks. The automatic synchronization of changes through Browsersync keeps your work in constant harmony with your browser view, eliminating the need for constant manual updates.

Boosting Collaboration

Gulp.js enhances your development environment, allowing you to focus on creative problem-solving rather than mundane tasks. The automatic synchronization of changes through Browsersync keeps your work in constant harmony with your browser view, eliminating the need for constant manual updates.

Optimizing Performance

Gulp.js is not just about speeding up your development process; it also contributes to the performance of your final product. The minification of assets, removal of debugging code, and efficient asset management result in a leaner and faster WordPress theme.

Enabling Innovation

By automating repetitive tasks, Gulp.js frees up your mental space to explore innovative ideas. With more time on your hands, you can experiment with new design concepts, explore intricate interactions, and fine-tune user experiences, ultimately crafting a theme that stands out in the competitive WordPress landscape.

Maintaining Best Practices

Gulp.js encourages adherence to best practices in coding and asset management. The seamless compilation of Sass into a unified CSS file, the strategic ordering and minification of JavaScript, and the efficient handling of images all contribute to a more organized and maintainable codebase.

Enhancing Site Maintenance

As your WordPress theme matures, Gulp.js continues to be your ally. When updates or changes are required, Gulp’s automation ensures that the same optimization and synchronization benefits persist, making the maintenance phase of your theme’s lifecycle much smoother.

In a nutshell, Gulp.js transforms WordPress theme development from a process laden with repetitive actions into a dynamic, automated, and efficient workflow. It empowers developers to concentrate on creativity and problem-solving, leaving the heavy lifting to the tool itself. With Gulp.js, the act of coding and refining a modern WordPress theme becomes an enjoyable journey that culminates in a high-quality, performant, and innovative end product. So, embrace Gulp.js, and watch as it revolutionizes not only your WordPress site but also your entire approach to web development.