Gulp watch is perfect for when you’re editing project files since it allows you to not have to run the gulp command manually each time. We’ll start off with a simple example by pulling in bootstrap-sass, and watching our SASS files merge and build as we make changes.

Example

First, let’s go ahead and start a new project and pull in bootstrap-sass.

yarn add bootstrap-sass

If you do not yet have a package.json file, make sure to run

yarn init

We’ll also need to add gulp.

yarn add gulp

To compile our SASS to CSS we’ll want to also include gulp-sass plugin.

yarn add gulp-sass

Next, let’s go ahead and setup our gulpfile.js and include our plugins along with some boiler plate from our previous article.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

vargulp=require('gulp');

varsass=require('gulp-sass');

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

// Copy SASS files to new location

gulp.src([

'./node_modules/bootstrap-sass/assets/stylesheets/*',

'./node_modules/bootstrap-sass/assets/stylesheets/*/*',

'./node_modules/bootstrap-sass/assets/stylesheets/*/*/*',

]).pipe(gulp.dest('./assets/sass/bootstrap/'));

// Convert SASS to CSS

gulp.src('./assets/sass/custom.scss')

.pipe(sass().on('error',sass.logError))

.pipe(gulp.dest('./css/'));

});

I went over in detail the process of building this file in my previous article Configuring Gulp On A New Project. The key thing to note here, is that we’re copying our bootstrap files to their new locations while also adding a file of our own called custom.scss, where we’ll make our specific changes.

I’ve included our custom.scss file as a reference as well, since we will be making our changes here for gulp.watch to check.

1

2

3

4

5

6

@import'bootstrap/bootstrap';

body{

background-color:green;

}

Now we need to add our watcher, this way we can simply just run gulp watch from the command line. We do this using the gulp.watch api as so.

1

2

3

4

gulp.watch('assets/sass/**/*.scss',[

'default'

]);

Now every time you run gulp, it will start the watcher and look for changes within the files as you make them.

You could essentially make a task for watch that would allow you to type gulp watch from the command line instead. For instance:

1

2

3

4

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

gulp.watch('./assets/sass/*.scss',['default']);

});

That’s all there is to it. You can be as creative as you want with your watchers. I’ve also included my full gulpfile.js file as reference.

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.