gulp使用浏览器同步构建,并且不会重新加载页面

时间:2017-08-04 20:20:37

标签: node.js reactjs gulp browser-sync

我有一个带有以下build任务的gulpfile:

var gulp = require('gulp'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    babelify = require('babelify'),
    browserify = require('browserify'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    bs = require('browser-sync').create('BrowserSync');

gulp.task('build', function () {
    return browserify({entries: './src/app.js', debug: true})
        .transform("babelify", { presets: ['es2015','react'] })
        .bundle()
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init())
        .pipe(uglify())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('./dist/js'))
        .pipe(bs.reload({stream: true}));
});

该过程完美地构建了我的文件,但是我的浏览器没有加载。为什么我的浏览器没有重新加载?我如何实现理想的行为?我觉得我错过了BrowserSync的一些内容。

注意:我非常自信BrowserSync正常工作,因为我在另一项任务中调用bs.reload(),页面重新加载完美。很高兴粘贴更多代码,但如果需要的话。

2 个答案:

答案 0 :(得分:1)

以下是一段starter project的片段,我开始讨论的是你所提到的......

/*...*/
gulp.task('watchify', () => {
  let args = merge(watchify.args, { debug: true })
  let bundler = watchify(browserify('./src/js/app.js', args)).transform(babelify, { presets: ["es2015", "react"] })
  bundle(bundler)

  bundler.on('update', () => {
    bundle(bundler)
  })
})


function bundle(bundler) {
  return bundler.bundle()
    .on('error', map_error)
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(rename('app.min.js'))
    .pipe(sourcemaps.init({ loadMaps: true }))
      // capture sourcemaps from transforms
      .pipe(uglify())
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest('./dist/js'))
    .pipe(sync.reload({
            stream: true
    }))
}
/*...*/

// watching multiple files with a task 'watch'
gulp.task('default', () => {
    gulp.watch('src/js/**/*.js', ['watchify']);
});

答案 1 :(得分:1)

启动browsersync的gulp任务由gulp运行,因为它是在默认任务中触发的。

然后我从终端手动运行gulp build,这就是问题所在。因此,此手动命令无权访问由默认gulp进程创建的browsersync实例。

因此,gulp build自动运行实例化版本就可以了。

相关问题