javascript - gulp 的 browser-sync 一直无法动态加载老是刷新页面,求解决。
習慣沉默
習慣沉默 2017-05-19 10:45:36
0
3
742

我弄的每次修改 js 或 html 文件,浏览器都会刷新页面。而不会重新加载。 这一点都不像网上说的

以下是我的代码:

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']);
習慣沉默
習慣沉默

全部回复(3)
过去多啦不再A梦

新的回答: // 评论区放不下
非常抱歉我没见过你这种写法,这是我对ionic 1.0版本进行的增强做法,你可以参考:

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);
  });
});

没见过这种用法,你看看官方文档的用法 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);
});
左手右手慢动作

还有没监听server?
然后少了change就reload?
gulp.watch("*.html").on("change", browserSync.reload);

滿天的星座

@鸿则 @小_u_酱 很感谢你的回复,我就如下修改(让人失望的是依旧没效果,每次修改js文件,浏览器依旧会刷新页面)

另外我的gulp版本是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']);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板