Enhancing your front-end development workflow using Gulp 4

Enhancing your front-end development workflow using Gulp 4CodeuixBlockedUnblockFollowFollowingApr 29Automating front-end development tasks using Gulp 4In this Article we will setup a sample project and implement the following tasks which will help us in speeding up the development process.

Initializing the serverReloading the browser automatically when changes are made to a file.

Using Scss preprocessor to convert Scss file to CSS file.

Optimizing CSS, JavaScript and images.

Auto prefixing to write vendor-free CSSWhat is Gulp?Gulp is a JavaScript toolkit which helps you in implementing multiple front end tasks during web development, it can be used to do wide range of things which can help you in reducing the development time.

You can create your own customized build process that suits your development needs.

Installing GulpBefore we install gulp you need to have Node.

js (Node) installed in your computer.

If Node.

js is not already installed in your computer, you can download the installer from Node’s website.

Once we’re done with installing Node, you can install Gulp using the following code in the command line tool.

// for windows usersnpm install gulp -g// for mac userssudo npm install gulp -gNote: Mac users should prepend the keyword sudo before the command in order for command to execute as administrator.

The npm install syntax used in the command specify to install Gulp onto your system using Node Package Manager (npm).

The -g flag specifies npm to install the Gulp package globally on your system, which will allow you to access the gulp command anywhere on your system.

Now that we have install Gulp, let’s create a project that uses Gulp.

Creating a ProjectFirstly, let’s create a folder called Gulp4 to serve as our project root.

Run the following command from inside the directory to initialize the project.

//initialize the projectnpm init The above command creates a file named package.

json which stores all the information about the project, like the dependencies used in the project, scripts to execute particular command.

npm init will prompt you the following:After creation of package.

json file, install gulp in your project using the following command.

npm install gulp –save-devHere we are installing Gulp as development dependency instead of installing it globally.

The keyword –save-dev will install the package and append the package name under dev dependency in package.

json file.

After the command execution is finished view your project folder, you will find a new folder name node_modules created.

You will also find gulp folder inside node_modules.

Now we’re ready to start working with the Gulp.

Before we do so, let’s decide on how we are going to use the gulp in the project, and directory structure of the project.

Determining Folder Structure of the ProjectGulp can flexible enough to work with any folder structure, for this article we will use the structure as follows.

In this structure, we will use src folder for development purposes, while dist (as in “distribution”) folder containing the optimized files for product site.

We should keep project structure in mind while we work on our Gulp configurations.

Now, we will create a gulp task in gulpfile.

js file which will store all Gulp configurations.

Creating our first Gulp TaskFirstly, we will require gulp in gulpfile.

jsconst gulp = require('gulp');Let’s create gulp task named hello which says “hello from gulp”gulp.

task('hello', function (done) {console.

log('hello from gulp');done();});The command line will return a log that outputs hello from gulp when the command gulp hello is executed.

Gulp tasks are usually more complex that this, it contains additional Gulp methods and Gulp plugins.

Here’s what a real task will look like:gulp.

task('task-name', function () { return gulp.

src('source-files') //Get source files .

pipe(aGulpPlugin()) //Send it through a gulp plugin .

pipe(gulp.

dest('destination')) //Output to destination})gulp.

src will tell the Gulp task what files to use for the task, while gulp.

dest tells Gulp where to output the files after completion of the task.

Preprocessing with GulpWe can compile Sass to CSS in Gulp with the use the plugin gulp-sass.

Firstly, install the plugin as dev dependency using the following command.

npm install gulp-sass –save-devWe will have to require gulp-sass from node_modules folder before we can use the plugin.

const sass = require('gulp-sass');Create a task named sass which compile scss file from the source and create a css file in the destination.

gulp.

task('sass', function () { return gulp.

src('src/scss/main.

scss') .

pipe(sass()) .

pipe(gulp.

dest('src/css')) })Now let’s edit main.

scss file and add a sass function.

//main.

scss$primary-color:#6c63ff;$font: 'lato';body{ background: $primary-color; font-family: $font; p{ color: #ffffff; }}If you run gulp sass in command line, you could see a new main.

css file was created in src/assets/css.

In addition you can view the compiled code written in the css file.

//main.

cssbody{ background: #6c63ff; font-family: 'lato';}body p{ color: #ffffff;}That’s great, we are now able to compile sass file to css file.

There are times when we want to compile using multiple Scss file into a single CSS file, we implement this by using regular expressions that specifies path also known as node globs.

Using Node GlobsGlobs are used for matching patterns in files that allows you to add more than one file into gulp.

src.

There are 4 different globbing patterns used in the workflow.

*.

scss: The * pattern is a wildcard that matches any file ending with “ .

scss ” in directory.

**/*.

scss: this version * pattern matches any file ending with .

scss in root folder and any child directories.

!not.

scss: the !.indicates gulp to exclude from its matches.

*.

+(scss|sass): the plus+ and parentheses () allows to match multiple patterns, which different pattern separated by pipe | Character.

Since we are aware of globs, we can replace src/scss/main.

scss with a src/scss/**/*.

scss pattern which matches any file with a .

scss extension in /scss or a child directory.

gulp.

task('sass', function () { return gulp.

src('src/scss/*.

scss') .

pipe(sass()) .

pipe(gulp.

dest('src/css')) })Now we can have multiple scss files that can be compiled to a css file by running gulp sass command.

Watching sass file for changesGulp provides you a method called which will watch for the changes in the file and execute certain function when a change is detected.

We will watch for any changes in scss file.

gulp.

watch('src/scss/**/*.

scss', gulp.

series('sass'));Here we will create gulp task named watch and place the watch method that needs to be watched, list can contain multiple watch processes.

gulp.

task('watch', function() { gulp.

watch('src/scss/**/*.

scss', gulp.

series('sass'));})Now run gulp watch in command line which will start watching for changes in scss files, when a change is made to the file it will automatically compile the scss to css.

Using Vendor free CSSWe can add vendor free css automatically while compiling scss to css by using gulp plugin called gulp-prefixer.

Installing the gulp plugin.

npm install gulp-autoprefixer –save-devNow let’s alter sass task to add vendor free css.

const autoprefixer = require('gulp-autoprefixer');gulp.

task('sass', function () { return gulp.

src('src/scss/*.

scss') .

pipe(sass()) .

pipe(autoprefixer()) .

pipe(gulp.

dest('src/css'))});Running gulp sass will compile scss to css and add vendor free css.

Live-reloading using Browser SyncBrowser Sync will help us make web development easier by spinning up the server that allows us to do live reloading easily.

Let’s start by installing browser sync as dev dependency.

npm install browser-sync –save-devAfter finishing the installation, we can start configuring gulp task for starting the server in gulpfile.

js file.

const browserSync = require('browser-sync').

create();gulp.

task('serve', function(){ browserSync.

init({ server: 'src', port: 4000 });})When we run gulp serve in command line the application will served in the respective port via the browser.

We will change our sass task slightly so Browser Sync can inject updated css styles into the browser.

gulp.

task('sass', function () { return gulp.

src('src/scss/**/*.

scss') .

pipe(sass()) .

pipe(autoprefixer()) .

pipe(browserSync.

reload{ stream:true }) .

pipe(gulp.

dest('src/css'))});Now we will configure the task that will watch for changes in sass files and reload the browser accordingly.

Step 1: creating browser reload function//Browser Reload Functiongulp.

task('reload', function(done){ browserSync.

reload(); done();})Step 2: altering watch function to reload the browsergulp.

task('watch', function() { gulp.

watch('src/scss/**/*.

scss', gulp.

series('sass','reload'));})Final step: create a live-server function.

gulp.

task('live-server', gulp.

series('serve', 'watch');Executing the command gulp live-server will start the server and reload the browser when a change is detected in any of the assets.

Optimizing the JavaScript and CSS files.

One of the major focus of the developer during production phase would be optimize the assets so the site can load faster, we can achieve this by minification.

Let’s assume we have included 2 script tags in index.

html<body> <!– build:js js/main.

min.

js –> <script src="js/main.

js"></script> <script src="js/custom.

js"></script> <!– endbuild –></body>We will use the gulp plugin called gulp-useref which concatenates any number of css and JavaScript files into a single file by looking for a comment that starts with “<! — build” and ends with “<! — endbuild — >”.

Its syntax is:<– build:<type> <path> –>.

.

.

.

.

.

( Html markup code for scripts )<!—endbuild –><type> can be either js, css.

It is necessary to set the type of file we are trying to concatenate.

<path> refers to the target path of the generated file.

setting up useref task which is similar to all other tasks we’ve done so far.

const useref = require('gulp-useref');gulp.

task('useref', function(){ return gulp.

src('src/*.

html') .

pipe(useref()) .

pipe(gulp.

dest('dist'))});Now let’s run useref task, Gulp will go through the 2 scripts and concatenate them into dist/js/main.

min.

js.

Let’s minify the JavaScript files by using gulp-uglify plugin and second plugin called gulp-if to ensure we only attempt to minify JavaScript files.

Installing the pluginnpm install gulp-uglify gulp-if –save-devModify useref task that minifies the JavaScript files in src folder.

const uglify = require('gulp-uglify');const gulpif = require('gulp-if');gulp.

task('asset-opt', function(){ return gulp.

src('src/*.

html') .

pipe(useref()) .

pipe(gulpif('*.

js', uglify())) .

pipe(gulp.

dest('dist'))});Minifying css files using gulp-csso plugin.

const gulpif = require('gulp-if');gulp.

task('asset-opt', function(){ return gulp.

src('src/*.

html') .

pipe(useref()) .

pipe(gulpif('*.

js', uglify())) .

pipe(gulp.

dest('dist'))});Copying files to DistLet’s consider there is folder name fonts inside src folder that contains all the fonts used in the project.

now create a function that copies the files from src to distgulp.

task('fonts', function(){ return gulp.

src('src/fonts/**/*') .

pipe(gulp.

dest('dist'))});running the command gulp fonts will copy the files to dist folder.

Combining Gulp tasksLet’s combine two or more task that needs to executed simultaneously, so particular task can be used in different occasions.

First set of task is for production, here we optimize all the assets files and copy the files from src to dist.

Create a task named build that combines two tasks named useref which optimizes files and fonts which copies the files to dist.

gulp.

task('build', gulp.

series('useref', 'fonts'));gulp build command will create dist folder with all the optimized assets for production site.

Second set of task is for development, here we compile sass to css, watch for any changes in the sass files and reload the browser using browser sync.

we will create a default gulp function that combines two tasks named serve and watch.

gulp.

task('default', gulp.

series('serve','watch'));Now run gulp default function by executing the command gulp, which will compile the files and serve it in the browser for development purpose.

Finally, here’s a github repo for all the work we’ve done!ConclusionWe’ve seen the basic working of Gulp and created a workflow that’s will compile Scss into CSS while watching files for changes at the same time.

We can run this task with the gulp command.

we’ve built a second task named build that create a dist folder for production site, we compiled sass to css, optimize all the assets and copy necessary folder to dist folder.

we can run this task by typing gulp build in the command line.

The workflow we’ve created is enough for most web developers.

Gulp has lot more to offer and make the development process more efficient.

Here are some ideas that we can implement:For Development:Creating sprites with sprityCompiling the files for which changes were made with gulp-changedWriting Javscript with the latest syntax with Babel or TraceurGenerating Modernizr script automatically with gulp-modrenizrUsing template engines like Pug to modularize HTMLFor Optimization:Removing usnused CSS with unCSSGenerating inline CSS with critical to improve the performanceLet us know what you felt about the article in the comments below.

If you have any questions on workflow.

We’ll be happy to reply!.

. More details

Leave a Reply