Search code examples
javascriptgulplivereloadgulp-watchgulp-livereload

Gulp-livereload, -webserver and -embedlr. How to use them together?


I try to understand how to use gulp with these useful and popular plugins. There are what I have:

  • runned go(lang) server on localhost:8000
  • static/local html files under app folder which are used by server to form pages
  • scss files under the same directory, which are converted into css and then autoprefixed

Here is my gulpfile.js:

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    watch = require('gulp-watch'),
    autoprefixer = require('gulp-autoprefixer'),
    livereload = require('gulp-livereload');

// "./" - it's "app" directory
gulp.task('default', function() {
    return gulp.src('./*.scss')
        .pipe(watch('./*.scss'))
        .pipe(sass())
        .pipe(autoprefixer('> 5%'))
        .pipe(gulp.dest('./'));
});

So what I need:

  • watch html, css/scss files for change and make reload on localhost:8000 (chrome's open tab)
  • it will be great if there is no need to use:
    • livereload chrome plugin
    • expressjs framework
  • reload html pages if it opened directly just like file without server

I've read that it is possible to achieve this by using gulp-embedlr and gulp-webserver. If so, how to do it?


Solution

  • Ok, the best solution that I find is using Gulp + BrowserSync! It's great solution.

    Here is the code of my gulpfile.js:

    var gulp = require('gulp'),
        sourcemaps = require('gulp-sourcemaps'),
        sass = require('gulp-sass'),
        watch = require('gulp-watch'),
        autoprefixer = require('gulp-autoprefixer'),
        browserSync = require('browser-sync'),
        reload = browserSync.reload;
    
    gulp.task('browserSync', function() {
        browserSync({
            //logConnections: false,
            //logFileChanges: false,
            notify: false,
            open: false,
            server: {
                baseDir: "./"
            }
        });
    });
    
    gulp.task('sass', function() {
        return gulp.src('./css/*.scss')
            .pipe(sourcemaps.init())
                .pipe(sass())
            .pipe(autoprefixer('> 5%'))
            .pipe(sourcemaps.write())
            .pipe(gulp.dest('./css'))
            .pipe(reload({stream:true}));
    });
    
    gulp.task('watch', function() {
        gulp.watch('./css/*.scss', ['sass']);
        gulp.watch('./*.html', reload);
    });
    
    gulp.task('default', ['watch', 'sass', 'browserSync']);
    

    There is no sense to explain the code above. Just read this: http://www.browsersync.io/docs/gulp/