In this article, we look at how you can use Gulp.js to automate a range of repetitive CSS development tasks to speed up your workflow.
Web development requires little more than a text editor. However, you’
ll quickly become frustrated with the repetitive tasks that are essential for a modern website and fast performance, such as:
- converting or transpiling
- minimizing file sizes
- concatenating files
- minifying production code
- deploying updates to development, staging and live production servers.
Some tasks must be repeated every time you make a change. The most infallible developer will forget to optimize an image or two and pre-production tasks become increasingly arduous.
Fortunately, computers never complain about mind-numbing work. This article demonstrates how use Gulp.js to automate CSS tasks, including:
- optimizing images
- compiling Sass .scss files
- handling and inlining assets
- automatically appending vendor prefixes
- removing unused CSS selectors
- minifying CSS
- reporting file sizes
- outputting sourcemaps for use in browser DevTools
- live-reloading CSS in a browser when source files change.
All the code is available from GitHub, and it works on Windows, macOS or Linux.
Why Use Gulp?
A variety of task runners are available for web projects including Gulp, Grunt, webpack and even npm scripts. Ultimately, the choice is yours and it doesn’t matter what you use, as your site/app visitors will never know or care.
Gulp is a few years old but stable, fast, supports many plugins, and is configured using JavaScript code. Writing tasks in code has several advantages, and you can modify output according to conditions — such as only minifying CSS when building the final files for live deployment.
Example Project Overview
The task code assumes Gulp 3.x will be used. This is the most recent stable version and, while Gulp 4 is available, it’s not the default on npm. If you’re using Gulp 4, refer to How do I update to Gulp 4? and tweak the gulpfile.js
code accordingly.
Image file sizes will be minimized with gulp-imagemin which optimizes JPG, GIF and PNG bitmaps as well as SVG vector graphics.
Sass .scss
files will be pre-processed into a browser-compatible main.css
file. Sass isn’t considered as essential as it once was, because:
- standard CSS now offers features such as variables (Custom Properties)
- HTTP/2 reduces the need for file concatenation.
That said, Sass remains a practical option for file splitting, organization, (static) variables, mixins and nesting (presuming you don’
t go too deep).
The resulting Sass-compiled CSS file will then be processed using PostCSS to provide further enhancements such as asset management and vendor-prefixing.
Getting Started with Gulp
If you’
ve never used Gulp before, please read An Introduction to Gulp.js. These are the basic steps for getting started from your terminal:
- Ensure Node.js is installed.
- Install the Gulp command-line interface globally with
npm i gulp-cli -g
. - Create a new project folder — for example,
mkdir gulpcss
— and enter it (cd gulpcss
). - Run
npm init
and answer each question (the defaults are fine). This will create apackage.json
project configuration file. - Create a
src
sub-folder for source files:mkdir src
.
The example project uses the following sub-folders:
src/images
— image filessrc/scss
— source Sass filesbuild
— the folder where compiled files are generated
Test HTML Page
This tutorial concentrates on CSS-related tasks, but an index.html
file in the root folder is useful for testing. Add your own page code with a <link>
to the final stylesheet. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Using Gulp.js for CSS tasks</title>
<link rel="stylesheet" media="all" href="build/css/main.css">
</head>
<body>
<h1>My example page</h1>
</body>
</html>
Module Installation
Most Node.js modules will be installed as project dependencies so the CSS can be built on development or production servers. To install Gulp and all plugins locally, do the following:
npm i gulp gulp-imagemin gulp-newer gulp-noop gulp-postcss gulp-sass gulp-size gulp-sourcemaps postcss-assets autoprefixer cssnano usedcss
Assuming you’
re using a recent version of npm
, all modules will be listed in the "dependencies"
section of package.json
.
browser-sync is installed as a development dependency since, it’s not required on live production servers:
npm i browser-sync --save-dev
The module will be listed in the "devDependencies"
section of package.json
.
Create a Gulp Task File
Gulp tasks are defined in a JavaScript file named gulpfile.js
. Create it, then open the file in your editor (VS Code is the current favorite). Add the following code:
(() => {
'use strict';
/**************** gulpfile.js configuration ****************/
const
// development or production
devBuild = ((process.env.NODE_ENV || 'development').trim().toLowerCase() === 'development'),
// directory locations
dir = {
src : 'src/',
build : 'build/'
},
// modules
gulp = require('gulp'),
noop = require('gulp-noop'),
newer = require('gulp-newer'),
size = require('gulp-size'),
imagemin = require('gulp-imagemin'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
sourcemaps = devBuild ? require('gulp-sourcemaps') : null,
browsersync = devBuild ? require('browser-sync').create() : null;
console.log('Gulp', devBuild ? 'development' : 'production', 'build');
})();
This defines a self-executing function and constants for:
devBuild
—true
ifNODE_ENV
is blank or set todevelopment
dir.src
— the source file folderdir.build
— the build folder- Gulp and all plugin modules
Note that sourcemaps
and browsersync
are only enabled for development builds.
Gulp Image Task
Create the src/images
folder then copy some image files into it or any subfolder.
Insert the following code below the console.log
in gulpfile.js
to create an images
processing task:
/**************** images task ****************/
const imgConfig = {
src : dir.src + 'images/**/*',
build : dir.build + 'images/',
minOpts: {
optimizationLevel: 5
}
};
gulp.task('images', () =>
gulp.src(imgConfig.src)
.pipe(newer(imgConfig.build))
.pipe(imagemin(imgConfig.minOpts))
.pipe(size({ showFiles:true }))
.pipe(gulp.dest(imgConfig.build))
);
Configuration parameters are defined in imgConfig
, which sets:
- a
src
folder to any image insidesrc/images
or a subfolder - a
build
folder tobuild/images
, and - gulp-imagemin optimization options.
A gulp.task
named images
passes data through a series of pipes:
- The source folder is examined.
- The gulp-newer plugin removes any newer image already present in the build folder.
- The gulp-imagemin plugin optimizes the remaining files.
- The gulp-size plugin shows the resulting size of all processed files.
- The files are saved to the
gulp.dest
build folder.
Save gulpfile.js
, then run the images
task from the command line:
gulp images
The terminal will show a log something like this:
Gulp development build
[16:55:12] Using gulpfile gulpfile.js
[16:55:12] Starting 'images'...
[16:55:12] icons/alert.svg 306 B
[16:55:12] cave-0600.jpg 47.8 kB
[16:55:12] icons/fast.svg 240 B
[16:55:12] cave-1200.jpg 112 kB
[16:55:12] cave-1800.jpg 157 kB
[16:55:12] icons/reload.svg 303 B
[16:55:12] gulp-imagemin: Minified 3 images (saved 205 B - 19.4%)
[16:55:12] all files 318 kB
[16:55:12] Finished 'images' after 640 ms
Examine the created build/images
folder to find optimized versions of your images. If you run gulp images
again, nothing will occur because only newer files will be processed.
The post How to Use Gulp.js to Automate Your CSS Tasks appeared first on SitePoint.
by Craig Buckler via SitePoint