HTML Reloading using BrowserSync in Gulp - gulp

I've tried several different things in my gulpfile.js to get HTML automatic reloading to work with BrowserSync (not LiveReload) in Gulp, but none have worked. I thought this last try would do the trick but it isn't working, either. What am I missing?
Here's my entire gulpfile.js:
// -------------------------------------------------------------------------
// GET THINGS SET UP
// -------------------------------------------------------------------------
// Include Gulp
var gulp = require('gulp');
// CSS plugins
var sass = require('gulp-sass');
var combineMediaQueries = require('gulp-combine-media-queries');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
// JS plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
// Image plugins
var imagemin = require('gulp-imagemin');
var svgmin = require('gulp-svgmin');
// General plugins
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var notify = require('gulp-notify');
// -------------------------------------------------------------------------
// TASKS
// -------------------------------------------------------------------------
// CSS tasks
gulp.task('css', function() {
return gulp.src('src/scss/**/*')
// Compile Sass
.pipe(sass({ style: 'compressed', noCache: true }))
// Combine media queries
.pipe(combineMediaQueries())
// parse CSS and add vendor-prefixed CSS properties
.pipe(autoprefixer())
// Minify CSS
.pipe(cssmin())
// Where to store the finalized CSS
.pipe(gulp.dest('build/css'))
// Notify us that the task was completed
.pipe(notify({ message: 'CSS task complete' }));
});
// JS tasks
gulp.task('js', function() {
return gulp.src('src/js/**/*')
// Concatenate all JS files into one
.pipe(concat('production.js'))
// Minify JS
.pipe(uglify())
// Where to store the finalized JS
.pipe(gulp.dest('build/js'))
// Notify us that the task was completed
.pipe(notify({ message: 'Javascript task complete' }));
});
// Image tasks
gulp.task('images', function() {
return gulp.src('src/images/raster/*')
// Minify the images
.pipe(imagemin())
// Where to store the finalized images
.pipe(gulp.dest('build/images'))
// Notify us that the task was completed
.pipe(notify({ message: 'Image task complete' }));
});
// SVG tasks
gulp.task('svgs', function() {
return gulp.src('src/images/vector/*')
// Minify the SVG's
.pipe(svgmin())
// Where to store the finalized SVG's
.pipe(gulp.dest('build/images'))
// Notify us that the task was completed
.pipe(notify({ message: 'SVG task complete' }));
});
// Watch files for changes
gulp.task('watch', ['browser-sync'], function() {
// Watch HTML files
gulp.watch('build/*.html', reload);
// Watch Sass files
gulp.watch('src/scss/**/*', ['css']);
// Watch JS files
gulp.watch('src/js/**/*', ['js']);
// Watch image files
gulp.watch('src/images/raster/*', ['images']);
// Watch SVG files
gulp.watch('src/images/vector/*', ['svgs']);
});
gulp.task('browser-sync', function() {
browserSync.init(['build/css/*', 'build/js/*'], {
server: {
baseDir: "build"
}
});
});
// Default task
gulp.task('default', ['css', 'js', 'images', 'svgs', 'watch', 'browser-sync']);

I had the exact same problem.
The problem was that my jade (html) task did not finish before my browsersync task.
So I made the browsersync task wait for all tasks that had to finish first
Apparently thats why Browser-Sync was not aware of the file, this fixed it:
gulp.task('browsersync', ['jade', 'stylus', 'browserify'], function() {
browserSync.init(['./public/**/**.**'], {
port: 8080,
server: {
baseDir: "./public"
}
});
});

gulp.task('browser-sync', function() {
browserSync.init(['./build/css/**.*', './build/js/**.*'], {
server: {
baseDir: "./build"
}
});
});
These minor changes in the code above, should fix your problem...

Related

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');
});
});

Gulp workflow for Express with SASS, BrowserSync, Uglify and Nodemon

Problems I'm facing:
The browser doesn't reflect live changes in .scss or .js
I don't understand whether we have to return the stream from the gulp.task() or not, I visited some websites and watched lectures some of which used return and some didn't.
Cannot understand the flow of execution of gulpfile (which statement runs first, then which and so on)
This is my current code of gulpfile.js.
"use strict";
var gulp = require('gulp');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
gulp.task('default', ['nodemon'], function(){
gulp.watch("src/sass/*.scss", ['sass']);
gulp.watch("src/js/*.js", ['js']);
gulp.watch("views/*.ejs").on('change',browserSync.reload); //Manual Reloading
})
// Process JS files and return the stream.
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('public/javascripts'));
});
// Compile SASS to CSS.
gulp.task('sass', function(){
// gulp.src('src/sass/*.scss') //without return or with return? why?
return gulp.src('src/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('public/stylesheets'))
.pipe(browserSync.stream());
});
// Setup proxy for local server.
gulp.task('browser-sync', ['js','sass'], function() {
browserSync.init(null, {
proxy: "http://localhost:3000",
port: 7000,
});
});
gulp.task('nodemon', ['browser-sync'], function(cb){
var running = false;
return nodemon({script: 'bin/www'}).on('start', function(){
if(!running)
{
running = true;
cb();
}
});
})
You may look at project structure at https://github.com/DivyanshBatham/GulpWorkflow
Try this:
"use strict";
var gulp = require('gulp');
var sass = require('gulp-sass');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
// First, run all your tasks
gulp.task('default', ['nodemon', 'sass', 'js'], function(){
// Then watch for changes
gulp.watch("src/sass/*.scss", ['sass']);
gulp.watch("views/*.ejs").on('change',browserSync.reload); //Manual Reloading
// JS changes need to tell browsersync that they're done
gulp.watch("src/js/*.js", ['js-watch']);
})
// create a task that ensures the `js` task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
browserSync.reload();
done();
});
// Process JS files and return the stream.
gulp.task('js', function () {
return gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('public/javascripts'));
});
// Compile SASS to CSS.
gulp.task('sass', function(){
return gulp.src('src/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('public/stylesheets'))
.pipe(browserSync.stream());
});
// Setup proxy for local server.
gulp.task('browser-sync', ['js','sass'], function() {
browserSync.init(null, {
proxy: "http://localhost:3000",
port: 7000,
});
});
gulp.task('nodemon', ['browser-sync'], function(cb){
var running = false;
return nodemon({script: 'bin/www'}).on('start', function(){
if(!running)
{
running = true;
cb();
}
});
})
Also, you should consider adding the JS file to your index.ejs
Eg: <script src='/javascripts/main.js'></script>
More help: https://browsersync.io/docs/gulp
I'll answer what I can.
You don't always have to return the stream in a gulp task but you should since you have some tasks, like 'browser-sync' that are dependent on other tasks, ['js','sass'], finishing. The purpose of returning the stream is to signal task completion. It is not the only way to signal task completion but one easy way.
You are already doing this in your ['js','sass'] tasks with the return statements.
Your 'js' task needs a .pipe(browserSync.stream()); statement at the end of it like your 'sass' task. Or try .pipe(browserSync.reload({stream:true})); sometimes that variant works better.
You have both browser-sync and nodemon running - that I believe is unusual and may cause problems - they do much the same thing and do not typically see them running together. I would eliminate nodemon from your file.
Flow of execution:
(a) default calls ['nodemon', 'sass', 'js'] : these run in parallel.
(b) nodemon call 'browser-sync'. 'browserSync' must finish setting up before 'nodemon' gets into its function.
(c) 'browser-sync', ['js','sass'], Here browser-sync is dependent upon 'js' and 'sass' which run in parallel and must finish and signal that they have finished by returning the stream for example before browser-sync continues.
(d) After 'js', 'sass', 'browser-sync' and 'nodemon' have completed, your watch statements are set up and begin to watch.

gulp-sass with browsersync inject not working

// variable
// -----------------------------------------------------------------------------
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
// task
// -----------------------------------------------------------------------------
gulp.task('styles', function() {
return gulp.src([
'./src/assets/styles/*.scss'
], {
base: './src/assets/styles/'
})
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dist/assets/styles/'))
.pipe(browserSync.stream());
});
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: './dist/'
}
});
gulp.watch('./dist/*.html').on('change', browserSync.reload);
gulp.watch('./src/assets/styles/**/*.scss', ['styles']);
gulp.watch('./dist/assets/scripts/*.js').on('change', browserSync.reload);
});
How can make above code working? The scripts and html part working, but scss part not, when scss file change, styles task has start and finish with no error, the html file has body tag, but the browser do not inject the new css file.
Check this example, it may help you with a few tweaks in paths:
/**
* This example:
* Uses the built-in BrowserSync server for HTML files
* Watches & compiles SASS files
* Watches & injects CSS files
*/
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gulp = require('gulp');
var sass = require('gulp-sass');
var filter = require('gulp-filter');
// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Sass task, will run when any SCSS files change.
gulp.task('sass', function () {
return gulp.src('scss/styles.scss')
.pipe(sass({includePaths: ['scss']})) // compile sass
.pipe(gulp.dest('css')) // write to css dir
.pipe(filter('**/*.css')) // filter the stream to ensure only CSS files passed.
.pipe(reload({stream:true})); // inject into browsers
});
// Default task to be run with `gulp`
gulp.task('default', ['sass', 'browser-sync'], function () {
gulp.watch("scss/*.scss", ['sass']);
});

Gulp - SCSS Lint - Don't compile SCSS if linting fails

Just wondering if someone can help me with my Gulp setup. At the moment I am using gulp-sass and gulp-scss-lint with a watch task. What I want to happen is that when an scss file is saved for the linting task to run completely and if any errors or warnings are thrown up for the scss files not to compile and for watch to continue running.
At the moment I seem to have this working with errors but not with the warnings, which still compile the stylesheets.
/// <binding ProjectOpened='serve' />
// Macmillan Volunteering Village Gulp file.
// This is used to automate the minification
// of stylesheets and javascript files. Run using either
// 'gulp', 'gulp watch' or 'gulp serve' from a command line terminal.
//
// Contents
// --------
// 1. Includes and Requirements
// 2. SASS Automation
// 3. Live Serve
// 4. Watch Tasks
// 5. Build Task
'use strict';
//
// 1. Includes and Requirements
// ----------------------------
// Set the plugin requirements
// for Gulp to function correctly.
var gulp = require('gulp'),
notify = require("gulp-notify"),
sass = require('gulp-sass'),
scssLint = require('gulp-scss-lint'),
gls = require('gulp-live-server'),
// Set the default folder structure
// variables
styleSheets = 'Stylesheets/',
styleSheetsDist = 'Content/css/',
html = 'FrontEnd/';
//
// 2. SASS Automation
// ------------------
// Includes the minification of SASS
// stylesheets. Output will be compressed.
gulp.task('sass', ['scss-lint'], function () {
gulp.src(styleSheets + 'styles.scss')
.pipe(sass({
outputStyle: 'compressed'
}))
.on("error", notify.onError(function (error) {
return error.message;
}))
.pipe(gulp.dest(styleSheetsDist))
.pipe(notify({ message: "Stylesheets Compiled", title: "Stylesheets" }))
});
// SCSS Linting. Ignores the reset file
gulp.task('scss-lint', function () {
gulp.src([styleSheets + '**/*.scss', '!' + styleSheets + '**/_reset.scss'])
.pipe(scssLint({
'endless': true
}))
.on("error", notify.onError(function (error) {
return error.message;
}))
});
//
// 3. Live Serve
// -------------
gulp.task('server', function () {
var server = gls.static('/');
server.start();
// Browser Refresh
gulp.watch([styleSheets + '**/*.scss', html + '**/*.html'], function () {
server.notify.apply(server, arguments);
});
});
// Task to start the server, followed by watch
gulp.task('serve', ['default', 'server', 'watch']);
//
// 4. Watch Tasks
// --------------
gulp.task('watch', function () {
// Stylesheets Watch
gulp.watch(styleSheets + '**/*.scss', ['scss-lint', 'sass']);
});
//
// 5. Build Task
// --------------
gulp.task('default', ['sass']);
Seems that #juanfran has answered this question on GitHub in 2015. I will just repost it here.
1) Using gulp-if you can add any condition you like.
var sass = require('gulp-sass');
var gulpif = require('gulp-if');
var scssLint = require('gulp-scss-lint')
gulp.task('lint', function() {
var condition = function(file) {
return !(file.scssLint.errors || file.scssLint.warnings);
};
return gulp.src('**/*.scss')
.pipe(scssLint())
.pipe(gulpif(condition, sass()));
});
2) Another more specific option is to use Fail reporter that will fail in case of any errors or warnings
gulp.task('scss-lint', function() {
return gulp.src('**/*.scss')
.pipe(scssLint())
.pipe(scssLint.failReporter());
});
gulp.task('sass', ['scss-lint'], function() {
return gulp.src('**/*.scss')
.pipe(scss());
});

Setting up BrowserSync to work with a build process and watch for changes

I am trying to create a basic gulp build process template that starts with an app folder containing html, sass, javascript, and image files and builds those files into a public folder. I am using gulp to watch the app folder for changes and then automatically refreshing the build process to the public folder.
I using browser-sync to serve the public folder and watch for changes but it doesn't seem to automatically reload when a change to the public folder is made. If I manually refresh the browser the changes are reflected.
Thanks for the help, see below for my gulp file:
//BASIC GULP FILE SETUP
//-------------------------------------------------------------
//Include Gulp
var gulp = require('gulp');
//General Plugins
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
var del = require('del');
var watch = require('gulp-watch');
var runSequence = require('run-sequence');
//CSS Plugins
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var csso = require('gulp-csso');
//JS Plugins
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
//HTML Plugins
var minifyHTML = require('gulp-minify-html');
//IMG Plugins
//-------------------------------------------------------------
//TASKS
//-------------------------------------------------------------
//Clean Public Folder
gulp.task('clean', function() {
del(['public/**/*']);
});
//CSS Tasks
gulp.task('sass', function () {
return gulp.src('app/sass/**/*.scss')
.pipe(sass())
.pipe(autoprefixer())
.pipe(csso())
.pipe(gulp.dest('public/css'));
});
//HTML Tasks
gulp.task('html', function () {
return gulp.src(['./app/**/*.html'], {
base: 'app'
})
.pipe(minifyHTML())
.pipe(gulp.dest('public'))
;
});
//Image Tasks
gulp.task('image', function () {
return gulp.src('app/img/**/*.{png,jpg,jpeg,gif,svg}')
.pipe(gulp.dest('public/images'));
});
//JS Tasks
gulp.task('js', function () {
return gulp.src('app/js/**/*.js')
.pipe(concat('main.js'))
.pipe(uglify())
.pipe(gulp.dest('public/js'));
});
// Watch files for changes
gulp.task('watch', function() {
// Watch HTML files
gulp.watch('./app/*.html', ['html'], browserSync.reload);
// Watch Sass files
gulp.watch('./app/sass/**/*.scss', ['sass'], browserSync.reload);
// Watch JS files
gulp.watch('./app/js/**/*', ['js'], browserSync.reload);
// Watch image files
gulp.watch('./app/img/*', ['image'], browserSync.reload);
});
gulp.task('browser-sync', ['watch'], function() {
browserSync.init({
server: {
baseDir: "./public"
}
});
});
gulp.task('defualt');
gulp.task('build', [], function(callback) {
runSequence('clean',
'sass',
'html',
'js',
'image');
});
I did a little more poking around the forums and the browser-sync documentation. In my serve task I needed to add a watch function to the Public directory that would manually call the reload every time a change was detected. So my 'browser-sync' task, now renamed 'serve', needs to look like this:
//Browser Sync Server
gulp.task('serve', ['watch'], function() {
browserSync.init({
server: {
baseDir: "./public"
}
});
gulp.watch("./public/**/*").on("change", browserSync.reload);
});
I am sure there is a way to do this with browser-sync's streams as well, but this manual reload method found in the docs has done the trick.
Try passing in a files object in the init function so it knows what to look for. No need for a different watch task, Browsersync does all that for you.
gulp.task('browser-sync', ['watch'], function() {
browserSync.init({
server: {
baseDir: "./public"
},
files: [
'**/*.css',
'**/*.js',
'**/*.html'
// etc...
]
});
});