Gulp 4 browsersync does not refresh when changing .less file - gulp

Link to Github repo: https://github.com/Greatshock/Netcracker-Study-Course/blob/f9bfb413929feec51064a78abf1450845f867186
I have a file named base.less, where all the styles are #import-ed. When I run the gulpfile (npm run dev), everything is being built, the browser opens the page. However, when I'm changing the content of one of the imported stylesheet, browsersync just writes in the console File event [change] : dist/base.css and nothing happens (even base.css does not actually change). Note that if I change base.less directly by writing some style in it, everything works fine.
Here is my gulpfile.js. Can anyone see the mistake?
'use strict';
const gulp = require('gulp'),
del = require('del'),
autoprefixer = require('gulp-autoprefixer'),
less = require('gulp-less'),
cleanCSS = require('gulp-clean-css'),
gulpIf = require('gulp-if'),
sourceMaps = require('gulp-sourcemaps'),
browserSync = require('browser-sync').create();
const isDevelopment = !process.env.NODE_ENV || process.env.NODE_ENV == 'development';
gulp.task('less', () => {
return gulp.src('src/assets/themes/base/base.less')
.pipe(gulpIf(isDevelopment, sourceMaps.init()))
.pipe(less())
.on('error', onLessError)
.pipe(autoprefixer({
browsers: [
'last 2 versions',
'safari 5',
'ie 10',
'ie 11'
],
cascade: true
}))
.pipe(cleanCSS())
.pipe(gulpIf(isDevelopment, sourceMaps.write()))
.pipe(gulp.dest('prod'));
});
gulp.task('images', () => {
return gulp.src('src/assets/themes/base/images/**/*.*', {base: 'src/assets/themes/base', since: gulp.lastRun('images')})
.pipe(gulp.dest('prod'));
});
gulp.task('index', () => {
return gulp.src('src/index.html', {since: gulp.lastRun('index')})
.pipe(gulp.dest('prod'));
});
gulp.task('clean', () => {
return del('prod');
});
gulp.task('build', gulp.series('clean', gulp.parallel('less', 'images', 'index')));
gulp.task('watch', () => {
gulp.watch('src/assets/themes/base/**/*.less', gulp.series('less'));
gulp.watch('src/assets/themes/base/images/**/*.*', gulp.series('images'));
gulp.watch('src/index.html', gulp.series('index'));
});
gulp.task('serve', function() {
browserSync.init({
server: 'prod'
});
browserSync.watch('prod/**/*.*').on('change', browserSync.reload);
});
gulp.task('dev', gulp.series('build', gulp.parallel('watch', 'serve')));
/***HELPERS FUNCTIONS***/
function onLessError(error) {
console.error(error.message);
this.emit('end');
}

I don't like this hackaround because to me it says one of our plugins isn't working correctly (browser-sync) so we correct it with that broken plugin. I'd maybe try browserify instead.
gulp.task('serve', function() {
browserSync.init({
files: [
{
match: ['src/assets/themes/base/**/*.less'],
fn: function (event, file) {
this.reload()
}
}
],
server: 'prod'
});
browserSync.watch('prod/**/*.*').on('change', browserSync.reload);
});
edit - This could also be a dir issue where the src is different than the watch dir. src/assets/themes/base/**/*.less' should be src/assets/themes/**/*.less' or src/assets/themes/base/*.less' for a distinct folder.
Edit 2- gulp.watch('src/assets/themes/base/*.less', gulp.series('less')); reloads base.less when any other file is changed if added to the gulp command. :D

Related

Infinite loop when running gulp watch

I have a Jekyll site which uses Gulp to compile the Jekyll files amongst other tasks such as compiling my sass, js files and running Browsersync. I'm migrating to Gulp 4.0 so have been updating my gulpfile.js to reflect this...however when I run 'gulp' in command line and update a Jekyll file, the build now loops infinitely. This only happens when I update a Jekyll file or a js file, not when I update a sass file. Here is my code:
var gulp = require('gulp'),
browserSync = require('browser-sync').create(),
sass = require('gulp-sass'),
babel = require('gulp-babel'),
autoprefixer = require('gulp-autoprefixer'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
svgmin = require('gulp-svgmin'),
sourcemaps = require('gulp-sourcemaps'),
cp = require('child_process'),
jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
// =======================================================================
// Browser Sync
// =======================================================================
gulp.task('browser-sync', function(done)
{
browserSync.init({
server: {
baseDir: "_site"
},
port: 3004,
open: false
});
done();
});
gulp.task('browser-sync-reload', function(done)
{
browserSync.reload();
done();
});
// =======================================================================
// SASS
// =======================================================================
var sassOptions = {
includePaths: ['scss'],
errLogToConsole: true,
outputStyle: 'compressed',
//sourceComments: 'map'
};
//Auto prefixer options
var autoPrefixerOptions = {
browsers: ['last 15 versions', '> 1%', 'ie 8', 'ie 7']
};
var styleInput = [
'_sass/**/_*.scss',
'_sass/site.scss'
];
gulp.task('sass-style', function()
{
return gulp.src(styleInput)
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer(autoPrefixerOptions, { cascade: true }))
.pipe(rename('styles.css'))
.pipe(gulp.dest('_site/css'))
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
});
// =======================================================================
// JS
// =======================================================================
var jsInput = [
'js/libs/**/*.js',
'js/site.js'
];
//Compile js to older browser compatible output
gulp.task('babel-js-min', function() {
return gulp.src(jsInput)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(concat('site.js'))
.pipe(uglify())
.pipe(rename('scripts.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_site/js/dist'))
.pipe(gulp.dest('js/dist'))
.pipe(browserSync.stream());
});
//Compile js to older browser compatible output
gulp.task('babel-js', function() {
return gulp.src(jsInput)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(concat('site.js'))
.pipe(rename('scripts.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_site/js/dist'))
.pipe(gulp.dest('js/dist'))
.pipe(browserSync.stream());
});
// =======================================================================
// SVGs
// =======================================================================
function onError(error)
{
console.log(error);
this.emit('end');
}
var svgInput = [
'_includes/svgs/src/**/*'
];
gulp.task('svgmin', function()
{
return gulp.src(svgInput)
.pipe(svgmin())
.on('error', onError)
.pipe(gulp.dest('./_includes/svgs/dist'));
});
// =======================================================================
// Jekyll
// =======================================================================
var jekyllFiles = [
'_includes/*.html',
'_layouts/*.html',
'**/*.md'
];
gulp.task('jekyll-build', function(done)
{
return cp.spawn("bundle", ["exec", "jekyll", "build"], { stdio: "inherit" }).on('close', done);
});
// =======================================================================
// Watch
// =======================================================================
gulp.task('watch', function()
{
gulp.watch(styleInput, gulp.series('sass-style'));
gulp.watch(jsInput, gulp.series('babel-js-min'));
gulp.watch(jsInput, gulp.series('babel-js'));
gulp.watch(svgInput, gulp.series('svgmin'));
gulp.watch(jekyllFiles, gulp.series('jekyll-build', 'browser-sync-reload'));
});
// =======================================================================
// Define the default task and add the watch task to it
// =======================================================================
gulp.task('default', gulp.parallel('watch', 'browser-sync'));
Any help with this would be appreciated.
I figured this out for anyone that has the same issue...my Jekyll child process was causing the infinite loop (only when editing a Jekyll file). Updating it to the following did the trick:
return cp.spawn(jekyll, ['build', '--incremental', '--drafts'], {stdio: "inherit"}).on('close', done);

gulp-file-include and BrowserSync Doesn't Reflect the Changes to Browser

I am trying to use gulp-file-include for include some common sections like header or footer from /src/includes folder into any .html pages in a project tree along with BrowserSync to refresh changes.
When I use gulp command from command line it's compiling all files into /dist folder without problems (I hope). But after, if I change anything from /src/index.html it doesn't reflect changes to browser or write changes into /dist/index.html.
I can't figure out exactly where the problem is. You can see the project from this Git repo and here is my gulpfile.js content:
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var browserSync = require('browser-sync').create();
var sourcemaps = require("gulp-sourcemaps");
var fileinclude = require("gulp-file-include");
// File Paths
var CSS_PATH = { src: "./src/sass/*.scss", dist: "./dist/css/"};
var JS_PATH = { src: "./src/js/*.js", dist: "./dist/js/"};
var HTML_PATH = { src: "./src/*.html", dist: "./dist/html/*.html"};
var INCLUDES_PATH = "./src/includes/**/*.html";
var JQUERY_PATH = "node_modules/jquery/dist/jquery.min.js";
// Error Handling
var gulp_src = gulp.src;
gulp.src = function() {
return gulp_src.apply(gulp, arguments)
.pipe(plumber(function(error) {
// Output an error message
gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.message));
// emit the end event, to properly end the task
this.emit('end');
})
);
};
// Styles
gulp.task('styles', function() {
return gulp.src(CSS_PATH["src"])
.pipe(sass())
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.init())
.pipe(gulp.dest(CSS_PATH["dist"]))
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(concat("main.css", {newLine: ""}))
.pipe(gulp.dest(CSS_PATH["dist"]))
.pipe(browserSync.reload({ stream: true }))
});
// Scripts
gulp.task('scripts', function() {
return gulp.src([JS_PATH["src"], JQUERY_PATH])
.pipe(uglify())
.pipe(concat('main.min.js'))
.pipe(gulp.dest(JS_PATH["dist"]));
});
// File Include
gulp.task('fileinclude', function() {
return gulp.src(HTML_PATH["src"])
.pipe(fileinclude({
prefix: '##',
basepath: 'src/includes'
}))
.pipe(gulp.dest('dist'));
});
// BrowserSync
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'dist/'
},
open: false,
browser: "Google Chrome",
notify: true,
notify: {
styles: {
top: 'auto',
bottom: '0',
borderRadius: '4px 0 0 0',
opacity: .9
}
},
snippetOptions: {
rule: {
match: /<\/body>/i,
fn: function (snippet, match) {
return snippet + match;
}
}
}
})
})
// Watch task
gulp.task('watch', ['fileinclude', 'browserSync'], function() {
gulp.watch(CSS_PATH["src"], ['styles']);
gulp.watch(JS_PATH["src"], ['scripts']);
gulp.watch(INCLUDES_PATH, ['fileinclude']);
gulp.watch([HTML_PATH["src"], HTML_PATH["src"]], browserSync.reload);
});
gulp.task('default', ['fileinclude', 'styles', 'scripts', 'browserSync', 'watch' ]);
I seem to have it working. I added the following to the end of the 'scripts' and 'fileinclude' tasks:
.pipe(browserSync.reload({ stream: true }))
// File Include
gulp.task('fileinclude', function() {
return gulp.src(HTML_PATH.src)
.pipe(fileinclude({
prefix: '##',
basepath: 'src/includes'
}))
.pipe(gulp.dest('dist'))
.pipe(browserSync.reload({ stream: true }))
});
// Scripts
gulp.task('scripts', function() {
// return gulp.src([JS_PATH["src"], JQUERY_PATH])
return gulp.src(JS_PATH.src)
.pipe(uglify())
.pipe(concat('main.min.js'))
.pipe(gulp.dest(JS_PATH.dist))
.pipe(browserSync.reload({ stream: true }))
});
so that the browser is reloaded after any changes to those two groups. I changed the 'watch' task to:
// Watch task
// gulp.task('watch', ['fileinclude', 'browserSync'], function() {
// 'browserSync' is already running from 'default' task so remove it from above
// 'fileinclude' is called below only where it is needed, not for changes to js/scss files
gulp.task('watch', function() {
gulp.watch(CSS_PATH.src, ['styles']);
gulp.watch(JS_PATH.src, ['scripts']);
gulp.watch(INCLUDES_PATH, ['fileinclude']);
// gulp.watch([HTML_PATH["src"], HTML_PATH["src"]], browserSync.reload);
// the above looks for changes to the source and immediately reloads,
// before any changes are made to the dist/html
// Watch for changes in the html src and run 'fileinclude'
// browserSync reload moved to end of 'fileinclude'
gulp.watch([HTML_PATH.src], ['fileinclude']);
});
Edit: to handle the subsequent question about gulp failing to watch new files, I have made some changes to my original answer. But you should really be using gulp4.0 now IMO. Gulp3.9.x relied on a library that was problematic in watching for new, deleted or renamed files.
You will need two more plugins:
var watch = require("gulp-watch");
var runSequence = require("run-sequence");
The gulp-watch plugin is better at watching for new, etc. files, but doesn't take 'tasks' as arguments but instead it takes functions as arguments so that is why I used run-sequence. [You could rewrite your tasks as regular functions - but then you might as well shift to gulp4.0].
Then use this 'watch' task:
gulp.task('watch', function () {
watch(CSS_PATH.src, function () {
runSequence('styles');
});
watch(JS_PATH.src, function () {
runSequence('scripts');
});
watch(INCLUDES_PATH, function () {
runSequence('fileinclude');
});
watch([HTML_PATH.src], function () {
runSequence('fileinclude');
});
});

pug file compiled to html does not livereload

In my project folder, I have pug files that are located in src/pug/*.pug, one of those files is index.pug. When compiled to html, the compiled files are located in build/templates/*.html. In the serve task, in browsersync.init(), I changed the baseDir from ./ to build/templates/ because the compiled index.html is located there. The problem is, browsersync livereload does not work; I have to refresh the browser just to see the changes I make in index.pug.
Gulpfile.js
const gulp = require('gulp'),
sass = require('gulp-sass'),
pug = require('gulp-pug'),
uglify = require('gulp-uglify'),
plumber = require('gulp-plumber'),
imagemin = require('gulp-imagemin'),
concat = require('gulp-concat'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync');
gulp.task('templates', () => {
return gulp.src('src/pug/*.pug')
.pipe(plumber())
.pipe(pug({pretty: true}))
.pipe(gulp.dest('build/templates/'))
.pipe(browserSync.stream({stream: true}));
});
gulp.task('styles', () => {
return gulp.src('src/sass/**/*.sass')
.pipe(plumber())
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(gulp.dest('build/css/all/'))
.pipe(concat('style.css'))
.pipe(gulp.dest('build/css/'))
.pipe(browserSync.stream({stream: true}));
});
gulp.task('scripts', () => {
return gulp.src('src/js/*.js')
.pipe(plumber())
.pipe(concat('script.js'))
.pipe(gulp.dest('build/js/'))
.pipe(browserSync.stream({stream: true}));
});
gulp.task('imagemin', () => {
gulp.src('assets/img/src/**/*')
.pipe(imagemin())
.pipe(gulp.dest('assets/img/dist/'));
});
gulp.task('serve', ['templates', 'styles', 'scripts'], () => {
browserSync.init({
server: {
baseDir: 'build/templates/'
},
notify: false
});
gulp.watch('src/pug/*.pug', ['templates']);
gulp.watch('src/sass/**/*.sass', ['styles']);
gulp.watch('src/js/*.js', ['scripts']);
gulp.watch('build/templates/index.html').on('change', browserSync.reload);
});
gulp.task('default', ['imagemin', 'serve']);
Can someone help me fix this?
Not sure why that doesn't work, but I have compared your build file to the official docs, and I came across this approach from the docs: Instead of watching the HTML files, it watches the source (pug files in your case) and calls browserSync.reload after that source compilation task has completed. In your case, the pug line would be replaced by something like this:
gulp.watch('src/pug/*.pug', ['templates-watch']);
And you would create a new task, called templates-watch, that would be defined as follows:
gulp.task('templates-watch', ['templates'], function (done) {
browserSync.reload();
done();
});

Gulp Sass Compiles Only With Two Saves

I've been trying to compile changes to #imports along with those to main SCSS files, and basically have this working.
The issue with my setup: To see changes, I must save files twice (irrespective of whether they're main files or imports). Ideas on this are greatly appreciated.
The directory structure is simply:
--> SCSS
--> SCSS/partials
Here are the relevant parts of my gulpfile:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var sync = require('browser-sync').create(); // create a browser sync instance.
var sassPaths = [
'bower_components/foundation-sites/scss',
'bower_components/motion-ui/src'
];
var paths = {
'assets': 'assets',
'dev': 'assets/styles/dev'
};
// DEV CSS
gulp.task('dev-styles', function() {
return gulp.src(['scss/**/*.scss', 'scss/*.scss'])
.pipe($.sass({
includePaths: sassPaths,
outputStyles: 'expanded'
})
.on('error', $.sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions', 'ie >=9']
}))
.pipe(rename({
suffix: '.dev'
}))
.pipe(gulp.dest('paths.dev'));
});
// DEFAULT WATCH
gulp.task('default', function() {
sync.init({
injectChanges: true,
proxy: 'localhost/basic-modx'
});
gulp.watch([ 'scss/**/*.scss', 'scss/*.scss' ], ['dev-styles']);
gulp.watch([ 'scss/**/*.scss', 'scss/*.scss' ]).on('change', sync.reload);
});
Your watches are set up oddly. I suspect that the second which reloads the browser finishes before the first which actually transpiles the scss, so nothing has changed when the reload occurs. Hence you have to hit save twice.
The better way from browserSync documentation is to have the reload at the end of your 'dev-styles' task like this:
gulp.task('dev-styles', function() {
return gulp.src(['scss/**/*.scss', 'scss/*.scss'])
.pipe($.sass({
includePaths: sassPaths,
outputStyles: 'expanded'
})
.on('error', $.sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions', 'ie >=9']
}))
.pipe(rename({
suffix: '.dev'
}))
.pipe(gulp.dest('paths.dev'));
.pipe(sync.stream());
});
and get rid of the second gulp.watch statement.

Gulp BrowserSync not working with SCSS

My gulp setup with browsersync seems to have a problem with detecting changes for SCSS files. It works perfectly fine for SLIM with reload and detection. There's no error with the gulp. The only problem is the browsersync fail to detect changes in SCSS file and reload or inject changes.
var gulp = require('gulp'),
sass = require('gulp-ruby-sass'),
slim = require('gulp-slim'),
autoprefix = require('gulp-autoprefixer'),
notify = require('gulp-notify'),
bower = require('gulp-bower'),
image = require('gulp-image'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
browserSync = require('browser-sync').create();
var config = {
sassPath: './source/sass',
slimPath: './source/slim',
bowerDir: './bower_components',
jsPath: './source/js'
}
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest(config.bowerDir))
});
gulp.task('js', function() {
return gulp.src('./source/js/**/*.js')
.pipe(concat('script.js'))
.pipe(gulp.dest('./dist/js'));
});
gulp.task('icons', function() {
return gulp.src(config.bowerDir + '/font-awesome/fonts/**.*')
.pipe(gulp.dest('./dist/fonts'));
});
gulp.task('image', function () {
gulp.src('./source/images/*')
.pipe(image())
.pipe(gulp.dest('./dist/images'));
} );
gulp.task('css', function() {
return sass('./source/scss/**/*.scss', {
style: 'compressed',
loadPath: [
'./source/scss',
config.bowerDir + '/bootstrap/scss',
config.bowerDir + '/font-awesome/scss',
]
}).on("error", notify.onError(function (error) {
return "Error: " + error.message;
}))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.stream());
});
gulp.task('html', function() {
gulp.src('./source/slim/**/*.slim')
.pipe(slim({
pretty: true
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('serve', ['css', 'html', 'js'], function() {
browserSync.init({
injectChanges: true,
server: "./dist"
});
gulp.watch(config.sassPath + '/**/*.scss', ['css']);
gulp.watch(config.slimPath + '/**/*.slim', ['html']).on('change', browserSync.reload);;
});
gulp.task('default', ['bower','js', 'icons', 'css', 'html', 'image', 'serve']);
gulp.task('build',['bower', 'js', 'icons', 'css', 'html', 'image'] );
This might not be the answer you are looking for but its the work around that I've been using since I ran into a similar issue using browserSync.stream() not firing off consistently.
'use strict';
var gulp = require('gulp'),
browserSync = require('browser-sync').create();
gulp.task('serve',function(){
browserSync.init({
server: {
baseDir: './dev/'
},
files: ['./dev/**/*.html',
'./dev/css/**/*.css',
'./dev/js/**/*.js',
'./dev/img/**/*.*'],
notify: false
});
});
As you can see, this uses browserSyncs own watch task as opposed to piping it through the entire build process, which can have its own advantages by making the serve task easily abstracted and pulled into another project.
Hope this helps.