简体   繁体   English

Gulp 浏览器同步只工作一次

[英]Gulp browser-sync only works once

I'm trying out Gulp on one of my projects and I wanted to run it like I used to with Grunt watch.我正在我的一个项目中试用 Gulp,我想像以前使用 Grunt 手表一样运行它。 Meaning, it has to watch less files and js files, lint, merge, compile and refresh the browser once all that is done.这意味着,一旦完成所有操作,它必须观看更少的文件和 js 文件、lint、合并、编译和刷新浏览器。

I managed to make it work with gulp-browser-sync but for some reason it only works once.我设法让它与 gulp-browser-sync 一起工作,但由于某种原因它只能工作一次。 I do a change to my .less file and the browser reloads.我对我的 .less 文件进行了更改,然后浏览器会重新加载。 Then, a second change, it does compile but no reload happens.然后,第二次更改,它确实编译但没有重新加载发生。

Here's the log:这是日志:

[BS] Serving files from: ./
[09:47:26] Starting 'css-clean'...
[09:47:26] Finished 'css-clean' after 16 ms
[09:47:26] Starting 'styles'...
[BS] 1 file changed (styles.min.css)
[09:47:27] Finished 'styles' after 624 ms
[09:47:27] Starting 'styles-watch'...
[BS] Reloading Browsers...

And when I hit save a second time:当我第二次点击保存时:

[09:47:31] Starting 'css-clean'...
[09:47:31] Finished 'css-clean' after 3.39 ms
[09:47:31] Starting 'styles'...
[BS] 1 file changed (styles.min.css)
[09:47:32] Finished 'styles' after 362 ms

As for the JS, it works all the time.至于 JS,它一直有效。 No issues whatsoever, even after the styles task is done, the JS changes are still triggering the reload properly.没有任何问题,即使在样式任务完成后,JS 更改仍会正确触发重新加载。 Really is only the styles that has issues.真的只有样式有问题。

Here's the gulpfile.js这是 gulpfile.js

var gulp = require('gulp'),
    autoprefixer = require('gulp-autoprefixer'),
    less = require('gulp-less'),
    minifycss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    notify = require('gulp-notify'),
    path = require('path'),
    streamqueue = require('streamqueue'),
    clean = require('gulp-clean'),
    browserSync = require('browser-sync').create(),
    reload = browserSync.reload;


// Clean the CSS folder
gulp.task('css-clean', function () {
    return gulp.src(['dist/css'], {read: false})
        .pipe(clean());
});

// Clean the CSS folder
gulp.task('js-clean', function () {
    return gulp.src(['dist/js'], {read: false})
        .pipe(clean());
});


// Generate the CSS styles, clean before hand
gulp.task('styles', ['css-clean'], function() {
  return streamqueue({ objectMode: true },
            gulp.src(['./bower_components/uikit/less/uikit.less']),
            gulp.src(['./src/less/main.less'])
        )
    .pipe(concat('styles.less'))
    .pipe(less({
      paths: [ path.join(__dirname, 'less', 'includes') ]
    }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe(gulp.dest('dist/css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gulp.dest('dist/css'))
    .pipe(browserSync.reload({stream:true}));
});

// create a task that ensures the `styles` task is complete before
// reloading browsers
gulp.task('styles-watch', ['styles'], browserSync.reload);



// Lint Task
gulp.task('lint', function() {
    return gulp.src('src/js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});


// Generate the scripts, clean before hand
gulp.task('scripts', ['js-clean', 'lint'], function() {
  return streamqueue({ objectMode: true },
            gulp.src(['./bower_components/jquery/dist/jquery.js']),
            gulp.src(['./bower_components/modernizer/modernizr.js']),
            gulp.src(['./bower_components/uikit/js/uikit.js']),
            gulp.src(['./src/js/plugin.js']),
            gulp.src(['./src/js/main.js'])
        )
    .pipe(concat('scripts.js'))
    .pipe(gulp.dest('dist/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('dist/js'))
    .pipe(browserSync.reload({stream:true}));
});

// create a task that ensures the `scripts` task is complete before
// reloading browsers
gulp.task('scripts-watch', ['scripts'], browserSync.reload);


// Lint Task
gulp.task('alldone', ['scripts'], function() {
    return gulp.src('src/js/*.js')
               .pipe(notify({ message: 'Gulp tasks are completed!!' }));
});


// Static server
gulp.task('browsersync', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });

    gulp.watch("src/less/*.less", ['styles-watch']);
    gulp.watch('src/js/*.js', ['lint', 'scripts-watch']);
    gulp.watch("*.html").on('change', reload);
});


// Default Task
gulp.task('default', ['css-clean', 'js-clean', 'styles', 'lint', 'scripts', 'alldone']);

// Build Task
gulp.task('build',   ['css-clean', 'js-clean', 'styles', 'lint', 'scripts', 'alldone']);

Thanks for your help!谢谢你的帮助!

How about directly use直接用怎么样

.pipe(browserSync.stream())

I once had the same problem while changing '.jade' files which it only reloaded once.我曾经在更改仅重新加载一次的“.jade”文件时遇到同样的问题。 Then I wrapped browserSync.reload in an anonymous function like然后我将browserSync.reload包装在一个匿名函数中,例如

gulp.task('templates-watch', ['templates'], function() {
    browserSync.reload();
});

It works for me.这个对我有用。 I don't know if there is something special about browserSync.reload .不知道browserSync.reload有没有什么特别之处。 How about have a try.试试怎么样。 :) :)

For me in Gulp 4, the anonymous function didn't solve the issue, What I did was wrap the browserSync.reload() in a function with a done callback:对于 Gulp 4 中的我来说,匿名函数没有解决问题,我所做的是将 browserSync.reload() 包装在一个带有完成回调的函数中:

function reload(done) {
  browserSync.reload();
  done();
}

gulp.watch(['scripts/**/*.js','!scripts/main.min.js'], gulp.series(buildScripts, reload));

I know this is not the right way to do things, but after some trial and error I figured out that using an undefined function after browserSync.reload()我知道这不是正确的做事方式,但经过反复试验后,我发现在browserSync.reload()之后使用未定义的函数

gulp.watch("./**/*.php", function () {
    browserSync.reload();
    done();
});

leads to a reference error in my log which triggers to reload the browser:导致我的日志中出现引用错误,触发重新加载浏览器:

ReferenceError: done is not defined 
    at ...
    at ...
    at asyncRunner (...)
    at processTicksAndRejections (...)
[Browsersync] Reloading Browsers...

Are you sure the CSS is not changed in the browser?你确定浏览器中的 CSS 没有改变吗? New styles are loaded without requiring to reload the page.无需重新加载页面即可加载新样式。 At least that is what my gulp setup is doing.至少这就是我的 gulp 设置正在做的事情。

Try changing the .less file, and see if the change is actually visible in the browser.尝试更改 .less 文件,看看更改是否真的在浏览器中可见。

My situation is a little different, but it might be similar enough to be helpful to you or someone else.我的情况有点不同,但它可能相似到足以对您或其他人有所帮助。 I have gulp + browserSync set up like this:我的 gulp + browserSync 设置如下:

.task('serve', ['clean', 'lint', 'sass', 'js', 'server'], function () {
  return gulp.watch([paths.js, paths.html, paths.sass], 
    ['lint', 'sass', 'js', browserSync.reload]);
})

This would start up and open the page once.这将启动并打开页面一次。 If I made a change to the HTML page and save it, I could see lint, sass, js, and browserSync.reload run, but the browser didn't refresh.如果我对 HTML 页面进行更改并保存,我可以看到 lint、sass、js 和 browserSync.reload 运行,但浏览器没有刷新。 My HTML was very simple;我的 HTML 非常简单; this:这个:

<!doctype html>
<html>
TEST
</html>

I changed the HTML to this finally and it started working:我终于把 HTML 改成了这个,它开始工作了:

<!doctype html>
<html>
<head>
    <title>TEST</title>
</head>
<body>
HELLO-TEST
</body>
</html>

I am facing same issue.looks there is issue with 'asyncDone' function inside node_modules.我面临同样的问题。看起来 node_modules 中的“asyncDone”函数存在问题。 here is file path: /node_modules/glob-watcher/index.js这是文件路径:/node_modules/glob-watcher/index.js

following is only dirty hack for temp fix.以下只是临时修复的肮脏黑客。 you may have issues sometimes.您有时可能会遇到问题。 but worked for me.但为我工作。

function onChange() {
  console.log("onChange running: ", running);

  /** existing code */

  // keeping this function at it worked for me.
  setTimeout(() => {
     runComplete({msg: "test"});
  }, 2000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM