search

Home  >  Q&A  >  body text

javascript - gulp's browser-sync has been unable to load dynamically and always refreshes the page. Please solve it.

Every time I modify a js or html file, the browser will refresh the page. without reloading. This is nothing like what is said on the Internet

The following is my code:

browserSync = require('browser-sync').create(),
 
 var htmlSrc = ['app/**/*.html', '!app/index.html', '!app/lib/**/*.html', '!app/lib/*.html'];
var jsSrc = ['app/**/*.js', '!app/lib/**/*.js', '!app/assets/**/*.js'];
var cssSrc = ['app/assets/**/*.css', '!app/lib/**/*.css'];

var imgSrc = ['app/assets/img/*', 'app/assets/img/**/*'];

var fontSrc = ['app/assets/fonts/**/*'];

var jsonSrc = ['app/translate/*.json', 'app/translate/**/*.json'];

var libSrc = ['app/lib/**/*'];

var indexSrc = 'app/index.html';

var buildPath = 'dist/';
var debugPath = 'app/';
 
 gulp.task('createIndex', function() {
    return gulp.src(indexSrc)
    .pipe(replace(/\.js/g, '.min.js'))
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest(buildPath))
    .pipe(browserSync.stream());
});

gulp.task('compressHTML', function() {
    return gulp.src(htmlSrc)
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest(buildPath))
    .pipe(browserSync.stream());
});

gulp.task('compressJS', function() {
    var filterIndex = filter(['**/app.config.js', '**/app.module.js', '**/app.route.oclazy.js'], {restore: true});
    return gulp.src(jsSrc)
    .on('error', function(err) {//语法检查,打印错误
        console.log('Error: ', err.message);
    })
    .pipe(filterIndex)
    .pipe(rename({suffix: '.min'}))
    .pipe(filterIndex.restore)
    .pipe(uglify())//压缩
    .pipe(gulp.dest(buildPath))
    .pipe(browserSync.stream());
});

gulp.task('compressCSS', function() {
    return gulp.src(cssSrc)
    //.pipe(concat('index.min.css')) 为了使用 oclazyload 不整合
    .pipe(minifycss())
    .pipe(gulp.dest(buildPath + 'assets'))
    .pipe(browserSync.stream());
});

gulp.task('compressJSON', function () {
    return gulp.src(jsonSrc)
        .pipe(jsonminify())
        .pipe(gulp.dest(buildPath + 'translate'))
        .pipe(browserSync.stream());
});

gulp.task('copyImg', function() {
    return gulp.src(imgSrc)
    .pipe(gulp.dest(buildPath + 'assets/img'))
    .pipe(browserSync.stream());
});

gulp.task('copyLib', function() {
    return gulp.src(libSrc)
    .pipe(gulp.dest(buildPath + 'lib'))
    .pipe(browserSync.stream());
});

gulp.task('copyFont', function() {
    return gulp.src(fontSrc)
    .pipe(gulp.dest(buildPath + 'assets/fonts'))
    .pipe(browserSync.stream());
});

gulp.task('clean', function() {
    return gulp.src(buildPath)
    .pipe(clean());
});

gulp.task('startCreate', ['clean'], function() {
    runSequence('createIndex', 
    ['compressHTML', 'compressJS', 'compressCSS', 'compressJSON'],
    ['copyLib', 'copyImg', 'copyFont']);
});

gulp.task('browserSync', function() {
    gulp.start('startCreate');

    browserSync.init({
        server: {
            baseDir: buildPath
        }
    });

    gulp.watch(indexSrc, ['createIndex']);
    gulp.watch(htmlSrc, ['compressHTML']);
    gulp.watch(jsSrc, ['compressJS']);
    gulp.watch(cssSrc, ['compressCSS']);
    gulp.watch(jsonSrc, ['compressJSON']);
});

gulp.task('default', ['browserSync']);
習慣沉默習慣沉默2753 days ago736

reply all(3)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:47:36

    New answer: // The comment area doesn’t fit
    I’m very sorry that I’ve never seen your way of writing. This is my enhancement to the ionic 1.0 version. You can refer to:

    var del = require('del');
    var gulp = require('gulp');
    var sass = require('gulp-sass');
    var watch = require('gulp-watch');
    var gutil = require('gulp-util');
    var babel = require('gulp-babel');
    var source = require('vinyl-source-stream');
    var buffer = require('vinyl-buffer');
    var assign = require('lodash.assign');
    var concat = require('gulp-concat');
    var rename = require('gulp-rename');
    var gulpIf = require('gulp-if');
    var uglify = require('gulp-uglify');
    var plumber = require('gulp-plumber');
    var options = require('./config/gulp.config');
    var htmlmin = require('gulp-htmlmin');
    var changed = require('gulp-changed');
    var minimist = require('minimist');
    var watchify = require('watchify');
    var browserify = require('browserify');
    var sourcemaps = require('gulp-sourcemaps');
    var browserSync = require('browser-sync');
    var autoprefixer = require('gulp-autoprefixer');
    
    var reload = browserSync.reload;
    var argv = minimist(process.argv.slice(2));
    // concat <> browserify
    var mode = argv.mode;
    var debug = argv.debug;
    
    var browserifyOptions = assign({}, watchify.args, {entries: [options.scripts.main] ,debug: argv.debug});
    var brify = watchify(browserify(browserifyOptions));
    brify.on('update', scriptsBundle);
    brify.on('log', gutil.log);
    gulp.task('scripts_browserify', scriptsBundle);
    function scriptsBundle(){
      return brify.bundle()
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source(options.scripts.outputFile))
        .pipe(buffer())
        .pipe(gulpIf(argv.debug ,sourcemaps.init({loadMaps: true})))
        .pipe(gulpIf(!argv.debug ,uglify()))
        // .pipe(gulpIf(!argv.debug ,rename({extname: ".min.js"})))
        .pipe(gulpIf(argv.debug ,sourcemaps.write('./')))
        .pipe(gulp.dest(options.scripts.dist))
        .pipe(gulpIf(argv.debug ,reload({stream: true})));
    }
    
    gulp.task('scripts_concat' ,() => {
      return gulp.src(options.scripts.src)
          .pipe(plumber())
          .pipe(gulpIf(argv.debug ,sourcemaps.init()))
          .pipe(babel({presets: ['es2015']}))
          .pipe(concat(options.scripts.outputFile))
          .pipe(gulpIf(!argv.debug ,uglify()))
          // .pipe(gulpIf(!argv.debug ,rename({suffix: ".min"})))
          .pipe(gulpIf(argv.debug ,sourcemaps.write('./')))
          .pipe(gulp.dest(options.scripts.dist))
          .pipe(reload({stream: true}));
    });
    
    gulp.task('templates' ,() => {
      return gulp.src(options.templates.src)
        .pipe(changed(options.templates.dist))
        .pipe(gulpIf(!argv.debug ,htmlmin()))
        .pipe(gulp.dest(options.templates.dist))
        .pipe(reload({stream: true}));
    });
    
    gulp.task('styles' ,['styles:fonts'] ,() => {
      return gulp.src(options.styles.main)
        .pipe(changed(options.styles.dist))
        .pipe(gulpIf(argv.debug ,sourcemaps.init()))
        .pipe(sass({outputStyle: argv.debug?'expanded':'compressed'}).on('error' ,sass.logError))
        .pipe(autoprefixer({
          browsers: ['last 2 versions', 'Android >= 4.0'] ,
          cascade: argv.debug ,
          remove:true
        }))
        .pipe(rename(options.styles.outputFile))
        // .pipe(gulpIf(!argv.debug ,rename(path => path.basename += '.min')))
        .pipe(gulpIf(argv.debug ,sourcemaps.write('./')))
        .pipe(gulp.dest(options.styles.dist))
        .pipe(reload({stream: true}));
    });
    
    gulp.task('styles:fonts' ,() => {
      return gulp.src(options.styles.fonts.src)
        .pipe(changed(options.styles.fonts.dist))
        .pipe(gulp.dest(options.styles.fonts.dist))
        .pipe(reload({stream: true}));
    });
    
    gulp.task('resources' ,() => {
      return gulp.src(options.resources.src)
        .pipe(changed(options.resources.dist))
        .pipe(gulp.dest(options.resources.dist))
        .pipe(reload({stream: true}));
    });
    
    gulp.task('images' ,() => {
      return gulp.src(options.images.src)
        .pipe(changed(options.images.dist))
        .pipe(gulp.dest(options.images.dist))
        .pipe(reload({stream: true}));
    });
    
    gulp.task('server' ,['templates' ,'styles' ,`scripts_${mode}` ,'images' ,'resources'] ,() => {
      browserSync.init(options.server);
      gulp.start('watch');
    });
    
    gulp.task('build' ,['templates' ,'styles' ,`scripts_${mode}` ,'images' ,'resources'] ,() => {});
    
    gulp.task('watch' ,() => {
      watch(options.styles.src , () => { gulp.start('styles'); });
      watch(options.styles.fonts.src , () => { gulp.start('styles:fonts'); });
      watch(options.scripts.src ,() => { gulp.start(`scripts_${mode}`); });
      watch(options.templates.src ,() => { gulp.start('templates'); });
      watch(options.resources.src ,() => { gulp.start('resources'); });
      watch(options.images.src ,() => { gulp.start('images'); });
      watch(['./www/index.html' ,'./www/js/logic.js'] ,() => {
        reload();
      });
    });
    
    gulp.task('clean' ,() => {
      return del(options.clean);
    });
    
    gulp.task('default' ,['clean'] ,() => {
      gulp.start(argv.debug?'server':'build' ,() =>{
        if(!argv.debug) process.exit(0);
      });
    });
    

    I have never seen this usage, please take a look at the official documentation http://www.browsersync.cn/doc...

    // 使用变量引用 `reload` 方法
    var reload = browserSync.reload;
    
    // 编译 SASS & 自动注入到浏览器
    gulp.task('sass', function () {
        return gulp.src('scss/styles.scss')
            .pipe(sass({includePaths: ['scss']}))
            .pipe(gulp.dest('css'))
            .pipe(reload({stream:true}));
    });
    
    // 监听scss和html文件, 当文件发生变化后做些什么!
    gulp.task('serve', ['sass'], function () {
    
        // 从这个项目的根目录启动服务器
        browserSync({
            server: {
                baseDir: "./"
            }
        });
    
        gulp.watch("scss/*.scss", ['sass']);
        gulp.watch("*.html").on("change", browserSync.reload);
    });

    reply
    0
  • ringa_lee

    ringa_lee2017-05-19 10:47:36

    Are you still monitoring the server?
    Then reload without change?
    gulp.watch("*.html").on("change", browserSync.reload);

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:47:36

    @红泽 @小_u_ Jiang Thank you very much for your reply. I will modify it as follows (disappointingly, it still has no effect. Every time I modify the js file, the browser will still refresh the page)

    In addition, my gulp version is 3.9.1

    gulp.task('createIndex', ['moveFavicon'], function() {
        return gulp.src(indexSrc)
        .pipe(replace(/\.js/g, '.min.js'))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest(buildPath))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('compressHTML', function() {
        return gulp.src(htmlSrc)
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest(buildPath))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('compressJS', function() {
        var filterIndex = filter(['**/app.config.js', '**/app.module.js', '**/app.route.oclazy.js'], {restore: true});
        return gulp.src(jsSrc)
        .on('error', function(err) {//语法检查,打印错误
            console.log('Error: ', err.message);
        })
        .pipe(filterIndex)
        .pipe(rename({suffix: '.min'}))
        .pipe(filterIndex.restore)
        .pipe(uglify())//压缩
        .pipe(gulp.dest(buildPath))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('compressCSS', function() {
        return gulp.src(cssSrc)
        //.pipe(concat('index.min.css')) 为了使用oclazyload不整合
        .pipe(minifycss())
        .pipe(gulp.dest(buildPath + 'assets'))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('compressJSON', function () {
        return gulp.src(jsonSrc)
            .pipe(jsonminify())
            .pipe(gulp.dest(buildPath + 'translate'))
            .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('copyImg', function() {
        return gulp.src(imgSrc)
        .pipe(gulp.dest(buildPath + 'assets/img'))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('copyLib', function() {
        return gulp.src(libSrc)
        .pipe(gulp.dest(buildPath + 'lib'))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('copyFont', function() {
        return gulp.src(fontSrc)
        .pipe(gulp.dest(buildPath + 'assets/fonts'))
        .pipe(browserSync.reload({stream:true}));
    });
    
    gulp.task('clean', function() {
        return gulp.src(buildPath)
        .pipe(clean());
    });
    
    gulp.task('startCreate', ['clean'], function() {
        runSequence('createIndex', 
        ['compressHTML', 'compressJS', 'compressCSS', 'compressJSON'],
        ['copyLib', 'copyImg', 'copyFont']);
    });
    
    gulp.task('browserSync', function() {
        gulp.start('startCreate');
    
        browserSync.init({
            server: {
                baseDir: buildPath
            }
        });
    
        gulp.watch(indexSrc, ['createIndex']).on("change", browserSync.reload);
        gulp.watch(htmlSrc, ['compressHTML']).on("change", browserSync.reload);
        gulp.watch(jsSrc, ['compressJS']).on("change", browserSync.reload);
        gulp.watch(cssSrc, ['compressCSS']).on("change", browserSync.reload);
        gulp.watch(jsonSrc, ['compressJSON']);
    });
    
    gulp.task('default', ['browserSync']);

    reply
    0
  • Cancelreply