Optimizing files with Gulp

Epilogue Of Gulp Series

gulp-1

Optimizing JavaScript and CSS

Optimizing JavaScript and CSS is done at two stages one is concatenation another one is minification. To concatenate files we will use the gulp-useref plugin and for the minification, we will use gulp-uglify for JavaScript and gulp-cssnano for CSS and additionally to check the file type we will use the gulp-if plugin. To concatenate files gulp offers yet another plugin called gulp-concatenate, but it is hard to concatenate files with this plugin if the files are located in different files.

This process takes all the targeted files and combine all the codes and generate a single file, it will avoid multiple requests to the server thus speed of the page load will significantly increase.

Read more about how concatenation improves page load?

Install the previously mentioned gulp plugins gulp-useref, gulp-uglify, and gulp-if by using the following command.

npm install gulp-uglify gulp-cssnano gulp-if gulp-useref --save-dev

Before we create and run the gulp-concatenate task, we should mention which scripts, stylesheet to be concatenated on html files. In our example we have the index.html page on app folder, as well we have two JavaScript files on js sub-folder and two stylesheet on css sub-folder of app folder, first include them in the index.html page using script tag and mark them as follows.

build

The comment starts with the build: and ends with endbuild, the suffix js after the word build tells the useref that the file type it’s going to concatenate is JavaScript and js/main.min.js is the name of the output file. The JavaScript files that exist between build tag is taken to concatenate by the useref while running the task, the same applies for CSS. Next, we will create the useref task on gulpfile.js.

gulp.task('useref', function(){
  return gulp.src('app/*.html')
    .pipe(useref())
    .pipe(gulpIf('*.js', uglify()))
    .pipe(gulpIf('*.css', cssnano()))
    .pipe(gulp.dest('dist'))
});

The gulp useref task takes all the html files and executes files that exists under the build comment, it concatenates and move ahead in the pipe and JavaScript output is minified using uglify() and CSS output is minified using cssnano() finally the minified files are saved under the dist folder.

Moving Fonts from app to dist folder

There is no need to optimize the font files since we can simply move them from app folder to the dist folder using the following task.

gulp.task('fonts', function(){
    return gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'))
});

This task will move all the font files exist under fonts folder to the dist/fonts folder.

Optimizing Images

To optimize images we will use gulp-imagemin plugin, we will install and create gulp task to optimize images, however compressing is time consuming task than other process since we will use gulp-cache to reduce, gulp-cache will ensure only the new or changed images get compressed. We will wrap the imagemin function using cache funtion

npm install gulp-imagemin gulp-cache --save-dev

gulp.task('images', function(){
    return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
        .pipe(cache(imagemin()))
        .pipe(gulp.dest('dist/images'))
});

Note: We can set interlace, optimization level with imagemin() function, head to plugin description for more details.

Cleaning up dist folder

Whenever we run useref task it generates a minified version of CSS and JavaScript with the latest modification(s), since before we save them into the dist folder we should clean up the folder, we will use del plugin from npm to clean up the dist folder.

npm install del --save-dev

gulp.task('clean:dist', function() {
    return del.sync('dist');
})

Note: Deleting images folder under dist won’t require for a fresh run of imagemin() function since we have cached the images using the cache().

So far we have created,

  • sass() to compile SASS to CSS
  • useref() to concatenate and minify JavaScript and CSS
  • images() to optimize images
  • fonts() to copy fonts to dis
  • clean:dist() to clean up dist folder

We have already grouped the browserSync and sass task together, now we will group all above mentioned task under the name build, we should execute these tasks sequentially as mentioned above, the run-sequence package from npm allows us to run gulp tasks one after one. We will install run-sequence package from npm and we will create build task with run-sequence.

npm install run-sequence --save-dev

gulp.task('build', function (callback) {
  runSequence('clean:dist', 
    ['sass', 'useref', 'images', 'fonts'],
    callback
  )
})

The build task first runs clean:dist to delete files exists under dist folder then runs rest of the task sequentially.

Remember, we have previously grouped the browserSync and sass task under watch task for consistency we would change the watch task as we have created build task.

gulp.task('default', function (callback) {
  runSequence(['sass','browserSync', 'watch'],
    callback
  )
})

Note, we have replaced the old name watch with new name default, further, we can run this grouped task by typing gulp simply instead mentioning the task name.

In this introductory tutorial, we have covered a few most useful Gulp plugins but there is a lot to explore. Gulp offers more than 3000 plugins, go head over to the official site of Gulp and explore more useful plugins which can help your pace of development.

Happy coding 🙂

Reloading browser with Gulp browser-sync

Automating Tasks

gulp-1

In this article, we will see how the watch method and browerSync help us to automate some repeated task like pre-processing. We will extend the gulp project we have created in previous articles.

Gulp provide watch method watch out for a file being saved, once a file is saved it call cited gulp task. Gulp watch method comes with gulp module since there is no need to install any npm_modules.

A typical gulp watch method seems as follows

gulp.task( 'files to watch out for change', [ tasks need to run ] )

We will create a gulp watch task as we created the gulp-sass task in the previous article.

gulp.task('watch', function(){
     gulp.watch('app/scss/*.sass', ['sass']);
});

The ‘*’ in front of ‘.sass’ the extension indicates any file that has the extension of ‘.sass’, in real time we will need to watch more than one file to run a specific task. Run the watch task and make the change on sass file we have on app folder, once we save the change on SASS file, CSS file will be updated instantly.

Note: Don’t delete the task sass which we created in the previous article, just paste the above watch task code below to the sass method.

Now everything is fine, we have created a SASS file and automated its compile process, but to make sure that the style is written properly we should head over to the browser and need to reload, Gulp provide us browser-sync plugin to automate this process, watch method observes file change and calls stated tasks, those tasks tells browser-sync to reload the browser page once they complete their task.

First, we will install gulp plugin browser-sync from npm_modules.

npm install browser-sync --save-dev

Create a variable to use browser-sync module.

var browserSync = require('browser-sync').create();

Next, we will create browser-sync task on gulpfile.js, at the end of each task the root of the server should be reloaded (in simple the folder where we have placed the index file), that folder should be mentioned base directory on the browser-sync task. A typical browser-sync task looks like the following

gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: 'app' 
    },
  })
})

We also need to change the sass task since the browser-sync will update the CSS in the browser. Make the change on sass task as mentioned below

gulp.task('sass', function() {
  return gulp.src('app/scss/**/*.sass') 
    .pipe(sass())
    .pipe(gulp.dest('app/css'))
    .pipe(browserSync.reload({
      stream: true
    }))
});

Finally, we should also do some tweaks on watch task, previously we have created watch task with the single argument and call back function, now will add up the second argument which is typically an array which has the list of task names those tasks will be executed before the watch task is initiated.

gulp.task('watch', ['browserSync', 'sass'], function (){
  gulp.watch('app/scss/**/*.scss', ['sass']); 
});

Everything is ready for now, all we need to do is testing our project by running the following command

gulp watch

Here look the change happens on the browser whenever the sass file is modified.

gulp

We will examine a few more plugins in the upcoming article.

Happy coding 🙂

Preprocessing with Gulp

Installing Gulp plugin and using them

gulp-1

In the previous article, we have created Gulp file with default task, we will learn to create a Gulp file to compile SASS file into CSS in this article.

First thing first, we need to install gulp plugin called gulp-sass in order to compile SASS file as CSS, this can be done by running the following command from your project root folder using the terminal.

npm install gulp-sass --save-dev

Don’t forget to add –save-dev flag which adds gulp-sass into devDependecies in the package.json file as well we have to add gulp-sass from the node_modules folder as we did with the gulp.

var sass = require('gulp-sass')

Now we’ll create a sample sass file, open a text editor and paste the following code and save as main.sass.

$primary-color: #3570ce 
$secondary-color: #1c9686
$text-color: #ffffff

.heading
	border-color: $secondary-color
	border: 1px solid
	background-color: $primary-color
	color: $text-color

All we need to do is creating a gulp task which helps us to compile the SASS file and produce CSS file, open the gulpfile.js that we have created earlier and create a new gulp task with following code, it takes SASS file and with the help of the gulp-sass plugin, it compiles the SASS into CSS.

gulp.task('sass', function(){ 
	return gulp.src('app/sass/main.sass') // Source of the sass file
	    .pipe(sass()) // Using gulp-sass plugin
	    .pipe(gulp.dest('app/css/')) // Compiled code to be saved here
});

Note: gulp-sass uses LibSASS to use Ruby methods gulp-ruby-sass plugin should be used instead above mentioned gulp plugin. This task is named as sass since we have loaded gulp-sass plugin from node_modules in the variable sass earlier.

Once you have done all the things, start the command prompt from the project root folder and run the sass gulp task using the following command.

gulp sass

For the above-given SASS style, the compiled CSS style will be the following

.heading {
  border-color: #1c9686;
  border: 1px solid;
  background-color: #3570ce;
  color: #ffffff;
 }

When we work on SASS in real time, there would be many modifications on SASS file, modifying SASS file and compiling them into CSS would time consuming task, it would be better if we automate this process, in the coming article, we would look how gulp tasks watch and browserSync helps to automate such tasks.

Happy Coding 🙂

Creating first Gulp project

Creating First Gulp Task

gulp-1

Welcome to the second article of Gulp for Beginners, in the previous article we have seen the way to install gulp in our local machine in this article we would create a Gulp project as well a gulp file with default task

Creating Project Root

We will create a folder on the desired location and name it as a project, this will serve the root folder for the project that we are going to create. Then navigate this folder on the command prompt, and type the following command.

npm init

This will prompt few details like project name, project version and a few more details about the project, it will create package.json which will contain information about the project. Once the package.json file is created we can install gulp to our project using the following command.

npm install gulp --save-dev

–save-dev flag is added with the npm command to install dev dependency. As of now, we have installed npm modules in our root folder. Next, we would set up a generic web app folder setup as follows.

A generic web app folder structure will look as follows,

|- app/
|- css/
|- fonts/
|- images/
|- index.html
|- js/
|- scss/
|- dist/
|- gulpfile.js
|- node_modules/
|- package.json

In this above folder structure, the app folder is intended for development purpose and dist folder is used to store optimized code for production. Now we will start to create gulpfile.js.

Creating gulpfile.js

gulpfile is simply a JavaScript file, open any text editor and create a gulpfile.js file and save at appropriate place as shown on the folder structure example above, add the following code on to the file and finally save.

var gulp = require('gulp');

gulp.task('default', function(){
    console.log('hello ') ;
});

require statement looks for gulp package on the node_modules folder and loads its contents if it found. On the second line of the above snippet, we are trying to create a gulp task which will just print the text hello. Head back to the terminal type gulp and hit enter, this will display the text hello on the command prompt.

Screenshot (230)

Note : The default task is the initial task that will executed when gulp
command is executed on the command prompt, if we name it as different
than default we should the name on command prompt.

eg: gulp function_name

We have created first simple gulp task but typically a gulp task would be bit complex than this, we will explore more gulp packages on upcoming articles.

Happy coding 🙂

Gulp for Beginners

Installing Gulp on Windows Machine

gulp-1

Gulp is an open-source JavaScript tool which automates the time-consuming and repetitive tasks that involve in web development such as minification, concatenation, unit testing, linting and so on.

There are plenty of tasks that gulp can carry out to minimize the work of the developer, head over to the official website of Gulp JS to check out the list of available plugins and their usage.

In this post we’d get to know about installing gulp-cli, creating and running first gulp task.

Installing gulp-cli

Gulp is built on Node.js and npm so before try to install gulp make sure that latest version of Node.js is installed on your machine, if not head over to the official website of node.js and install the appropriate version of node.js.

Reading recommendation Installing Node.js on Windows PC

Open up the command prompt (windows machine) and type the following command to install gulp-cli

npm install gulp-cli -g

Note: -g flag let npm to install gulp-cli globally which allows us to access and use gulp from anywhere computer.

Once your download completed you can check the version of gulp-cli to make sure that you have installed gulp-cli on your machine using the following command

gulp -v

Happy coding 🙂