Search code examples
gulpgulp-watch

Run server function before watch function


creating the server with gulp-connect plugin.

the Code is fine, but when I run gulp, it start monitor the 'watch' how can I run the server and run the watch function after creating the server.

var gulp = require("gulp"),
scss = require("gulp-scss"),
jsmin = require("gulp-jsmin"),
rename = require("gulp-rename"),
connect = require("gulp-connect");

var path = {
    src: {
        js: 'dist/js/**/*.js',
        css: 'dist/css/**/*.scss',
        img: 'dist/img/*.*',
        html: '/**/*.html'
    },
    build: {
        js: './js/',
        css: './css/',
        img: './img/'
    }
};

/* connect server */
gulp.task("connect", function () {
    connect.server({
        root: './',
        livereload: true
    });
});

/* SASS into css */
gulp.task("styles", function () {
    gulp.src(path.src.css)
        .pipe(scss())
        .pipe(gulp.dest(path.build.css))
        .pipe(connect.reload());
});

/* minified JS */
gulp.task("scripts", function () {
    gulp.src(path.src.js)
        .pipe(jsmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(path.build.js))
        .pipe(connect.reload());
});

/* html */
gulp.task("html",function(){
    gulp.src(path.src.html)
        .pipe(connect.reload());
});

/* watch */
gulp.task('watch', function(){
    gulp.watch([path.src.html],["html"]);
    gulp.watch([path.src.css],["styles"]);
    gulp.watch([path.src.js],["scripts"]);
});

gulp.task("default", ["connect", 'html', 'styles', 'scripts','watch']);

If I skip the watch function then gulp create the server. Any Help!!!


Solution

  • Change this :

    gulp.task("default", ["connect", 'html', 'styles', 'scripts', 'watch']);
    

    to:

    gulp.task("default", ['html', 'styles', 'scripts', 'watch']);
    

    and

    gulp.task('watch', ['connect'], function(){
      gulp.watch([path.src.html],["html"]);
      gulp.watch([path.src.css],["styles"]);
      gulp.watch([path.src.js],["scripts"]);
    }); 
    

    Now the 'connect' task will run before the 'watch' task starts. I think that is what you want? Also, add return statements to all your tasks. As in

    gulp.task("styles", function () {
      return gulp.src(path.src.css) ...........