How to write gulp tasks?

Hydroid
2 min readSep 5, 2020

This story will help you understand what gulp is and how you can write a gulp task.

What is Gulp?

Gulp is a build tool that helps us with web development tasks mainly frontend tasks. Few examples:

  • Converting ES6 to ES5 (Transpilation)
  • Reloading the browser automatically whenever a file is saved.
  • Optimizing assets like JS, Images, CSS, etc.
  • Code Minification
  • Code Uglification
  • Running a web server.

Install Gulp

sudo npm install gulp -g

Here,

-g means you are installing gulp globally in your system.

If you want to install gulp in your project only then use:

npm install gulp --save-dev

gulpfile.js

Create a file called gulpfile.js in your root directory of the project.

Lets write our first gulp task:

The first step is to require the gulp dependency in your gulpfile.js.

var gulp = require('gulp');

The require function tells the node to look inside the node_modules folder for a package name gulp. Now we can write a gulp task as:

gulp.task('task-name'), function () { 
// code here for what to do
}

Let’s test our gulp task:

gulp.task('hello-world'), function () { 
console.log('Hello World');
}

To run the above task just type in your terminal:

gulp hello-world

Note: You can add the gulp tasks in package.json also and run using npm.

You can see in the command line as output:

Hello World

Now, as we wrote our first code. Let’s write some complex gulp tasks.

Usually, gulp provides us two methods and a bunch of gulp plugins.

gulp.task('task-name', function () {
return gulp.src('source-files')
.pipe(aGulpPlugin())
.pipe(gulp.dest('destination'));
});

You can pipe many gulp plugin in a gulp task as you need.

To see your output, if it worked or not you can go inside your destination folder and see.

If you like this article and it was helpful to you. You can buy me a coffee just click on the below button.

--

--

Hydroid

Currently working as a Full Stack Developer in India