GULP:如何在不刷新的情况下更新浏览器(仅适用于 CSS 更改)

gulp: how to update the browser without refresh (for css changes only)

本文关键字:浏览器 适用于 CSS 更改 更新 情况下 刷新 GULP      更新时间:2023-09-26

我已经设置了gulp,以便在我进行更改时浏览器重新加载。但是,对于 css 更改,我希望浏览器在不刷新的情况下更新,但我不确定如何做到这一点。对于我当前的设置,我使用了本教程:

var debug = require('gulp-debug'),
    connect = require('gulp-connect'),
    watch = require('gulp-watch'),
    livereload = require('gulp-livereload');
gulp.task('webserver', function () {
    connect.server({
        livereload: true,
        root: ['demo/']
    });
});
gulp.task('livereload', function () {
    gulp.src(['index.html', 'resources/**/*.js'])
        .pipe(watch(['resources/**/*.html', 'index.html']))
        //.pipe(debug({verbose: true}))
        .pipe(connect.reload());
});
gulp.task('watch', function () {
    livereload.listen();
    gulp.watch('resources/**/*.scss', ['css']);
});

在我的 css 任务中,我也调用

.pipe(livereload());

任何建议我需要修改,以便 css 更新无需刷新即可发生?

更新:这是我的css任务(有点简化(:

gulp.task('css', function () {
    ...
    return gulp.src('demo.scss')
        .pipe($.sass({
            errLogToConsole: true
        }))
        .pipe(gulp.dest('./target/')
        .pipe(livereload());
});

当发生变化时,您需要调用livereload.changed(files)。为此,请参阅gulp-watch文档。

watch('**/*.js', function (files) {
  livereload.changed(files)
});

您可能需要一个 chrome 扩展程序来获取 gulp-livereload

我和你有同样的问题,我解决了。

我发现在gulp-connect中使用嵌入式实时加载支持是不受控制的。

因此,我尝试使livereload独立工作。

只需设置您的gulp-connect配置而无需livereload,并使用指定的主机选项调用livereload.listen(大多数情况下它应该是"localhost"(。喜欢

livereload.listen({ host: 'localhost' });

然后监视要检测的文件。喜欢

var changedFile = null;
gulp.task("livereload", function(cb){
    return gulp.src(changedFile)
        .pipe(plumber())
        .pipe(livereload());
});
gulp.watch(['*.css']).on('change', function(file) {
  changedFile = file.path;
  // run specific task according to the given file's extension
  // gulp.start(['livereload']);
});