【发布时间】:2015-08-26 22:21:34
【问题描述】:
我想为我的项目使用相同的 gulpfile.js,其中我使用预编译器 (sass)和 用于纯 css 中的较旧/较小的项目。 我也使用浏览器同步,我想注入 css到浏览器中(而不是重新加载整个页面)。
我的以下配置有效,即当我编辑 sass 文件时,它会编译并注入已编译的 css,而当我编辑 css 文件时,它会正确注入它。但是一个小细节仍然让我感到沮丧:当我编辑一个 sass 文件时,浏览器同步被通知 2 次 css 文件已更改。 1 次在 sass 观察者中,1 次在 css 观察者中.这对他来说似乎不是问题,因为它在我的浏览器中正确地注入了 css。但这不是很“干净”。
我想找到一种方法对此进行某种排除。理想情况下,只需在我的编码中添加更多逻辑,无需添加其他一些包,例如 gulp-watch、gulp-if...
var gulp = require('gulp'),
rubySass = require('gulp-ruby-sass'),
sourcemaps = require('gulp-sourcemaps'),
browsersync = require('browser-sync').create();
gulp.task('rubySass', function() {
return rubySass('sources/', {
style: 'expanded',
sourcemap: true
})
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: '/sources'
}))
.pipe(gulp.dest('./css'))
.pipe(browsersync.stream({match: "**/*.css"}));
// If I remove this line, browser-sync is still notified 2 times
// (the console is still showing 2 times "[BS] 1 file changed (main.css)")
// but, moreover, the css is no longer injected : the whole page is reloading.
});
gulp.task('browsersync', function() {
browsersync.init({
server: './',
logConnections: true
});
});
gulp.task('default', ['rubySass', 'browsersync'], function (){
gulp.watch('**/*.html', browsersync.reload);
gulp.watch('**/*.php', browsersync.reload);
gulp.watch('js/**/*.js', browsersync.reload);
gulp.watch('**/*.css', function(file){
console.log("In gulp watch : css");
gulp.src(file.path)
.pipe(browsersync.stream());
});
gulp.watch('./sources/**/*.scss', ['rubySass']).on('change', function(evt) {
console.log("In gulp watch : sass");
});
});
这是保存 sass 文件时的控制台输出:
正如我们所见,我们在 2 个 watchers 中连续输入,browser-sync 说 2 次“[BS] 1 file changed (main.css)”。
【问题讨论】:
-
我猜,但这可能是因为您没有异步运行任务(因为 gulp 默认运行所有任务同步)。另一件事是它可能是一个回调问题。
标签: css sass gulp browser-sync