How to make a refresh in browser with gulp

2019-03-24 22:10发布

问题:

I have an app is in iis, it is an app made in angularjs and webapi C # 2.0, I would like to create a task that updates the browser as soon as I save any js file.

Version of gulp: 3.9.1

gulp.task('livereload', function () {
    gulp.watch(config.files.js);
});

回答1:

gulp-livereload

A lightweight gulp plugin for livereload to be used with the livereload chrome extension or a livereload middleware.

Simple to setup:

var gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload');

gulp.task('less', function() {
  gulp.src('less/*.less')
    .pipe(less())
    .pipe(gulp.dest('dist'))
    .pipe(livereload());
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('less/*.less', ['less']);
});

Browsersync

There's no official Browsersync plugin for Gulp, because it's not needed! You simply require the module, utilise the API and configure it with options.

The new cool kid, most have already moved to it.

Streams are supported in Browsersync, so you can call reload at specific points during your tasks and all browsers will be informed of the changes. Because Browsersync only cares about your CSS when it's finished compiling - make sure you call .stream() after gulp.dest.

var gulp = require('gulp'),
    browserSync = require('browser-sync').create(),
    sass = require('gulp-sass');

// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {

    browserSync.init({
        server: "./app"
        // or
        // proxy: 'yourserver.dev'
    });

    gulp.watch("app/scss/*.scss", ['sass']);
    gulp.watch("app/*.html").on('change', browserSync.reload);
});

// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
    return gulp.src("app/scss/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("app/css"))
        .pipe(browserSync.stream());
});

gulp.task('default', ['serve']);

For a manual reload:

// ...
var reload = browserSync.reload;

// Save a reference to the `reload` method

// Watch scss AND html files, doing different things with each.
gulp.task('serve', function () {

    // Serve files from the root of this project
    browserSync.init({/* ... */});

    gulp.watch("*.html").on("change", reload);
});

Why Browsersync is better?

It is not constrained to a single device, it works across desktop and mobile devices at the same time. It will update code changes, synchronize scroll positions and form inputs automatically across all browsers and devices.