Search code examples
node.jsgulpgulp-watch

Configure Gulp 'watch' task for very basic server-restart (Node JS)


I'm trying to get the Gulp 'watch' task to restart the server when I make a change to a controller file.. to pick up those changes w/out having to manually restart the server.

Can someone post a small example with instructions to run it correctly?


Solution

  • So there are a lot of great tutorials out there, but IMHO they seem to not break down the step-by-step details that a newbie to Gulp like myself is looking for. This post assumes the reader has a basic understanding of how to set up paths with node JS, and aims to address only those perceived gaps with existing Gulp reference out there.

    Below is a complete gulpfile.js that handles

    • server restart
    • minification

    How to Run the Gulp Tasks

    A) Start the server with gulp.

    $ gulp
    

    or

    $ gulp dev
    

    Make some change to a file and see it restart

    B) Run the minify task

    $ gulp minify_js
    

    In your node setup, look in the corresponding directory for the generated file bundle.js

    gulpfile.js

    'use strict';
    
    var gulp = require('gulp'),
         jshint = require('gulp-jshint'),
         concat = require('gulp-concat'),
         uglify = require('gulp-uglify'),
         rename = require('gulp-rename'),
         nodemon = require('gulp-nodemon'),
         minifyCss = require('gulp-minify-css'),
         sourcemaps = require('gulp-sourcemaps'),
         plugins = require('gulp-load-plugins')();
    
    
    gulp.task('dev', function () {
      return plugins.nodemon({
        watch: ['config','controllers', 'models', 'util', 'routes', 'server.js'],
        script: 'server.js'
      });
    });
    
    gulp.task('minify_js', function() {
          return gulp.src('public/js/*.js')
            .pipe(sourcemaps.init())
              .pipe(concat('bundle.js'))
              //only uglify if gulp is ran with '--type production'
              // .pipe(gutil.env.type === 'production' ? uglify() : gutil.noop()) 
              .pipe(uglify()) 
            .pipe(sourcemaps.write())
            .pipe(gulp.dest('public/js'));
        });
    
    gulp.task('default', ['dev']);