我想为我使用预编译器(sass)的项目和纯 css 中的较旧/较小的项目使用相同的gulpfile.js。我也使用浏览器同步,我想将 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 个观察者中连续输入,browser-sync 说 2 次“[BS] 1 file changed (main.css)”。