Gulp livereload reloads the entire page when only CSS has changed - gulp-livereload

I've added livereload to my Gulp task. Its working except when I edit a CSS file the entire page is refreshed, not just the pages CSS.
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var sizereport = require('gulp-sizereport');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var run = require('run-sequence');
gulp.task('watch-theme-css', ['theme-css'], function () {
livereload.listen();
watch(themeFiles.sass, batch(function (events, done) {
gulp.start('theme-css', done);
}))
});
var themeFiles = {
sass: [
'mysite/base/sass/*.s+(a|c)ss',
'mysite/content/sass/*.s+(a|c)ss',
'mysite/custom/sass/*.s+(a|c)ss'
],
out: {
css: 'mysite/build'
}
};
gulp.task('theme-css', function () {
return gulp.src(themeFiles.sass)
.pipe(gulpif(env === 'development', sourcemaps.init()))
.pipe(sass().on('error', sass.logError))
.pipe(minifyCss({
compatibility: 'ie8'
}))
.pipe(gulpif(env === 'dev', sourcemaps.write('.')))
.pipe(gulp.dest(themeFiles.out.css))
.pipe(livereload());
});
Update Ive tried the following code from the link below but it does the same thing. http://www.roelvanlisdonk.nl/?p=4675
gulp.task('watch-theme-css', ['theme-css'], function () {
livereload.listen();
watch(themeFiles.sass, batch(function (events, done) {
gulp.start('theme-css', done);
}), ["reloadCss"]);
});
Same behaviour from this: https://laracasts.com/discuss/channels/tips/proper-way-to-use-livereload-with-laravel-elixir
gulp.task('watch-lr-css', ['theme-css'], function () {
livereload.changed(themeFiles.sass);
});
I tried the following but when I try and turn on the live reload browser plugin it says it cannot find the live reload server.
gulp: how to update the browser without refresh (for css changes only)
gulp.task('watch-theme-css', ['theme-css'], function () {
//livereload.listen();
livereload.changed(themeFiles.sass);
watch(themeFiles.sass, batch(function (events, done) {
gulp.start('theme-css', done);
}));
});

I spent a few hours on this last night and came across this: https://github.com/vohof/gulp-livereload/issues/93.
Looks like it's because of your sourcemaps. gulp-livereload tries to be smart and only reloads the css if there are only css changes. Otherwise it reloads the whole page because it thinks there are more files that changed.
So you just filter your glob down to only css before you call the livereload() function.
So something like this might help:
var filter = require('gulp-filter');
...
gulp.task('theme-css', function () {
return gulp.src(themeFiles.sass)
.pipe(gulpif(env === 'development', sourcemaps.init()))
.pipe(sass().on('error', sass.logError))
.pipe(minifyCss({
compatibility: 'ie8'
}))
.pipe(gulpif(env === 'dev', sourcemaps.write('.')))
.pipe(gulp.dest(themeFiles.out.css))
// Add filter here
.pipe(filter('**/*.css'))
.pipe(livereload());
});

You need to call livereload.changed(files) when change happens. To do that see gulp-watch doc.
watch('**/*.js', function (files) {
livereload.changed(files)
});

Related

After upgrade to Gulp 4 default task is not detecting default changes for JS & Scss

I upgraded the gulp to 4.0.2 from Gulp version 3. it will not detect changes when the tracked JSa and SCSS file is changed.
Gulp version I am using :-
CLI version: 2.3.0
Local version: 4.0.2
gulpfile.js
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
del = require('del'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
livereload = require('gulp-livereload'),
http = require('http'),
st = require('st'),
sourcemaps = require('gulp-sourcemaps'),
ngAnnotate = require('gulp-ng-annotate'),
babel = require('gulp-babel'),
uglifycss = require('gulp-uglifycss'),
browserSync = require('browser-sync').create();
//Rerun the task when a file changes
var watch_hintJs = ['./global/util/*.js', './global/util/**/*.js', './modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'];
var watch_hintscss = ['./global/scss/*.scss', './modules/**/*.scss'];
// This method is used to delete the files
gulp.task('clean', ()=> {
return del(['./assets/css']);
});
var globalCSS = ['./assets/libs/css/**','./assets/libs/css/*.css'];
gulp.task('css', ()=> {
return gulp.src(globalCSS)
.pipe(concat('myapp-main-libs.css'))
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
/* SASS TO CSS CONVERSION*/
gulp.task('sass', ()=> {
return gulp.src(['./global/scss/*.scss', './global/scss/lib/*.scss', './modules/**/*.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(sass())
.pipe(concat('myapp-main.css'))
//.pipe(strip())
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
//This method is converting all JS files to Single file//
var jsFiles = ['./global/util/*.js', './global/util/lib/*.js', './global/util/components/*.js',
'./modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'],
jsDest = './assets/js/',
jsLibs = [
'assets/libs/js/tether.min.js',
'assets/libs/js/jquery.min.js',
'assets/libs/js/jquery-ui-min.js',
'assets/libs/js/bootstrap.min.js',
'assets/libs/js/angular.min.js',
'assets/libs/js/angular-ui-router.min.js',
'assets/libs/js/ui-grid-min.js',
'assets/libs/js/html2canvas.js',
'assets/libs/js/ui-bootstrap-tpls-2.5.0.min.js',
'assets/libs/js/accordian.js',
'assets/libs/js/angularResizable.js',
'assets/libs/js/angular-animate.min.js',
'assets/libs/js/ngToast.js',
'assets/libs/js/angular-sanitize.js',
'assets/libs/js/pubsub.js',
'assets/libs/js/angular-environment.js',
'assets/libs/js/deferred-with-update.js',
'assets/libs/js/multiselect.js',
'assets/libs/js/angular-chart.min.js',
'assets/libs/js/common.js',
'assets/libs/js/bootstrap-colorpicker-module.min.js',
'assets/libs/js/dom-to-image.js',
'assets/libs/js/alasql.min.js',
'assets/libs/js/xlsx.core.min.js',
'node_modules/babel-polyfill/dist/polyfill.min.js',
'assets/libs/js/jquery.csv.js',
'assets/libs/js/z-worker.js',
'assets/libs/js/zip.js'
];
gulp.task('libs', ()=> {
return gulp.src(jsLibs)
.pipe(strip())
.pipe(concat('myapp-lib-scripts.js'))
.pipe(gulp.dest(jsDest));
});
var minify = require('gulp-minify');
gulp.task('scripts', ()=> {
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015', 'stage-3'],
"plugins": ["transform-async-to-generator"]
}))
.pipe(concat('myapp-scripts.js'))
.pipe(uglify({
mangle: false
}))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest(jsDest))
.pipe(livereload());
});
/*jshint, watch, browserify*/
// configure the jshint task
gulp.task('jshint', ()=> {
return gulp.src(watch_hintJs)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('browser-sync', gulp.series('sass', ()=> {
browserSync.init({
server: {
injectChanges: true,
baseDir: "./"
},
browser: ["chrome.exe"]
});
}));
gulp.task('js-watch', gulp.series('scripts', () =>{
console.log('you changed the JS');
return browserSync.reload();
}));
gulp.task('css-watch', gulp.series('sass', ()=> {
console.log('you changed the css');
return browserSync.reload();
}));
gulp.task('watch', gulp.series('browser-sync', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs, ['js-watch']);
gulp.watch(watch_hintscss, ['css-watch']);
gulp.watch(watch_hintJs, browserSync.reload());
return livereload.listen();
}));
gulp.task('server', (done)=> {
return http.createServer(
st({
path: __dirname + '/',
index: 'index.html',
cache: false
})
).listen(8080, done);
});
var revts = require('gulp-rev-timestamp');
gulp.task('rev-timestamp', ()=> {
return gulp.src("./index.html")
.pipe(revts())
.pipe(gulp.dest('.'));
});
gulp.task('default', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'rev-timestamp', 'watch'));
gulp.task('prod', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'jshint', 'rev-timestamp'));
Note: Style task is working correctly and moving all .scss files from source to destination.
I really appreciate any help since I am running out of ideas
Finally, I found the solution as below:-
gulp.task('watch', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs).on('change',gulp.parallel('js-watch'));
gulp.watch(watch_hintscss).on('change',gulp.parallel('css-watch'));
return livereload.listen();
});

Gulp Browsersync is not working for scripts.js file

I am new to Gulp watch and I'm facing the issue of Browsersync that is only refreshed for first time only when I run the "gulp watch" command and it only works for HTML,CSS files but not for scripts.js files.
I made this change on glop-watcher/index file
function onChange() {
console.log("onChange running: ", running); // custom changing
if (running) {
if (opt.queue) {
queued = true;
}
// custom changing
setTimeout(() => {
runComplete({msg: "custom code is working"});
}, 2000);
return;
}
now its refreshed the HTML,CSS file but still not working for scripts.js file at all even if refresh manually. Please help
Here is my gulpfile.js file
var gulp = require('gulp'),
settings = require('./settings'),
webpack = require('webpack'),
browserSync = require('browser-sync').create(),
postcss = require('gulp-postcss'),
rgba = require('postcss-hexrgba'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
mixins = require('postcss-mixins'),
colorFunctions = require('postcss-color-function');
gulp.task('styles', function() {
return gulp.src(settings.themeLocation + 'css/style.css')
.pipe(postcss([cssImport, mixins, cssvars, nested, rgba, colorFunctions, autoprefixer]))
.on('error', (error) => console.log(error.toString()))
.pipe(gulp.dest(settings.themeLocation));
});
gulp.task('scripts', function(callback) {
webpack(require('./webpack.config.js'), function(err, stats) {
if (err) {
console.log(err.toString());
}
console.log(stats.toString());
callback();
});
});
gulp.task('watch', function() {
browserSync.init({
notify: false,
proxy: settings.urlToPreview,
ghostMode: false
});
gulp.watch('./**/*.php', function() {
browserSync.reload();
});
gulp.watch(settings.themeLocation + 'css/**/*.css', gulp.parallel('waitForStyles'));
gulp.watch([settings.themeLocation + 'js/modules/*.js', settings.themeLocation + 'js/scripts.js'], gulp.parallel('waitForScripts'));
});
gulp.task('waitForStyles', gulp.series('styles', function() {
return gulp.src(settings.themeLocation + 'style.css')
.pipe(browserSync.stream());
}))
gulp.task('waitForScripts', gulp.series('scripts', function(cb) {
browserSync.reload();
cb()
}))
Finally, after 2 weeks of drilling into gulp I found the problem and solution too.
Here is the path of my .js files that gulp is watching
" .\myProject\wp-content\themes\myProject-theme\js "
but for gulp watch the path should be like this
" ./wp-content/themes/myProject-theme/js/*.js "
It does not include the main folder name/ root folder name. In my case the root folder where all my wordpress files lives is " myProject " and I mistakenly wrote it in gulp path that trouble me so much.
So be sure about your paths and also add this in onChange() function of glop-watcher/index file that is in the node_modules folder.
function onChange() {
console.log("onChange running: ", running);
if (running) {
if (opt.queue) {
queued = true;
}
// Add this code
setTimeout(() => {
runComplete({msg: "custom code is working"});
}, 2000);
return;
}

Getting error event.js:174 throw er; everytime I save any scss file

Here's a Screen Shot of the error event.js:174
I did a lot of research and googled a lot. I tried uninstalling and re-installing everything. Made new files again but still no luck. I tried on my laptop and it works smoothly without any errors. I am using Windows 7 64 bit desktop.
Am I doing anything wrong in Gulp? Here's the gulp code:
const gulp = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const browserSync = require('browser-sync').create();
const concat = require('gulp-concat');
const minify = require('gulp-minify');
const rename = require('gulp-rename');
const imagemin = require('gulp-imagemin');
const sourcemaps = require('gulp-sourcemaps');
const postcss = require('gulp-postcss');
//const webp = require('gulp-webp');
const log = require('fancy-log');
const g = require("gulp-load-plugins")();
const purgecss = require('gulp-purgecss');
const critical = require('critical').stream;
gulp.task('purgecss', () => {
return gulp.src('./dist/css/*.css')
.pipe(purgecss({
content: ["./dist/*.html"]
}))
.pipe(gulp.dest('./dist/css/purged'))
})
// Extract Media Queries & Make Seperate CSS Files
gulp.task("extractmedia", function() {
gulp.src("./dist/css/*.css")
.pipe(g.extractMediaQueries())
.pipe(gulp.dest("./dist/css/"));
});
// CSS Tasks
gulp.task('css-compile', function() {
gulp.src('scss/**/*.scss')
.pipe(sass({outputStyle: 'nested'}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 10 versions'],
cascade: false
}))
.pipe(gulp.dest('./dist/css/'));
});
gulp.task('minify-css', function() {
gulp.src(['./dist/css/*.css', '!dist/css/*.min.css'])
.pipe(cleanCSS())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./dist/css'))
});
// JavaScript Tasks
gulp.task('js-build', function() {
const plugins = getJSModules();
return gulp.src(plugins.modules)
.pipe(concat('modules.js'))
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('js-minify', function() {
gulp.src(['./dist/js/*.js', '!dist/js/*.min.js'])
.pipe(minify({
ext:{
src:'.js',
min:'.min.js'
},
noSource: true,
}))
.pipe(gulp.dest('./dist/js'));
});
// Image Compression
gulp.task('img-compression', function() {
gulp.src('./img/*')
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
imagemin.jpegtran({progressive: true}),
imagemin.optipng({optimizationLevel: 5}),
imagemin.svgo({
plugins: [
{removeViewBox: true},
{cleanupIDs: false}
]
})
]))
//.pipe(webp())
.pipe(gulp.dest('./dist/img'));
});
// Generate & Inline Critical-path CSS
gulp.task('critical', function () {
return gulp.src('./dist/*.html')
.pipe(critical({base: './dist/', inline: true, css: ['./dist/css/app.min.css']}))
.on('error', function(err) { log.error(err.message); })
.pipe(gulp.dest('./dist/'));
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src("dist/scss/*.scss")
.pipe(sass())
.pipe(gulp.dest("dist/css"))
.pipe(browserSync.stream({match: '**/*.css'}))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(postcss([ autoprefixer({ browsers: [
'Chrome >= 35',
'Firefox >= 38',
'Edge >= 12',
'Explorer >= 10',
'iOS >= 8',
'Safari >= 8',
'Android 2.3',
'Android >= 4',
'Opera >= 12']})]))
.pipe(sourcemaps.write())
.pipe(gulp.dest('css/'))
.pipe(cleanCSS())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('css/'))
});
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync.init({
injectChanges: true,
server: "./dist"
});
gulp.watch("dist/scss/*.scss", ['sass']);
gulp.watch("dist/*.html").on('change', browserSync.reload);
});
gulp.task('default', ['serve'], function() {
gulp.watch("scss/**/*.scss", ['css-compile']);
gulp.watch(["dist/css/*.css", "!dist/css/*.min.css"], ['minify-css']);
gulp.watch("js/**/*.js", ['js-build']);
gulp.watch(["dist/js/*.js", "!dist/js/*.min.js"], ['js-minify']);
gulp.watch("**/*", {cwd: './img/'}, ['img-compression']);
});
function getJSModules() {
delete require.cache[require.resolve('./js/modules.js')];
return require('./js/modules');
}
Please Help I am Stuck. As every time I save scss file I get this error all of a sudden which sucks hell lot of time for me to develop further. Sometimes it works fine but after 3-4 save file it crashes.
Found the Solution: It was all about the Folder Permissions. Hope this helps someone.

gulp build with browser sync and react not reloading page

I have a gulpfile with the following build task:
var gulp = require('gulp'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
babelify = require('babelify'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
bs = require('browser-sync').create('BrowserSync');
gulp.task('build', function () {
return browserify({entries: './src/app.js', debug: true})
.transform("babelify", { presets: ['es2015','react'] })
.bundle()
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/js'))
.pipe(bs.reload({stream: true}));
});
The process builds my files perfectly, however my browser does not load. Why doesn't my browser reload? And how do I achieve the desired behavior? I feel like I am missing something about BrowserSync.
NOTE: I am fairly confident BrowserSync is working properly as I call bs.reload() in another task, and the page reloads perfectly. Happy to paste in more code however if needed.
Here is a snippet from a starter project that I started a while back that does what you are mentioning...
/*...*/
gulp.task('watchify', () => {
let args = merge(watchify.args, { debug: true })
let bundler = watchify(browserify('./src/js/app.js', args)).transform(babelify, { presets: ["es2015", "react"] })
bundle(bundler)
bundler.on('update', () => {
bundle(bundler)
})
})
function bundle(bundler) {
return bundler.bundle()
.on('error', map_error)
.pipe(source('app.js'))
.pipe(buffer())
.pipe(rename('app.min.js'))
.pipe(sourcemaps.init({ loadMaps: true }))
// capture sourcemaps from transforms
.pipe(uglify())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/js'))
.pipe(sync.reload({
stream: true
}))
}
/*...*/
// watching multiple files with a task 'watch'
gulp.task('default', () => {
gulp.watch('src/js/**/*.js', ['watchify']);
});
The gulp task that started browsersync was run by gulp as it was triggered in the default task.
Then I ran gulp build manually from the terminal, and here was the issue. This manual command thus did not have access to the instance of browsersync that was created by the default gulp process.
So having gulp build run automatically with the instantiated version available did the trick.

Error when running Mocha tests with mochaphantom js in a Durandal environment

I have a problem including mocha tests in a durandal environment. I want to run my tests with mocha-phantomjs from the command line. The test works perfectly in the browser but as soon as I'm trying to use mocha-phantomjs I'm getting the following error message (command: mocha-phantomjs dummyPage.htm):
Error: Your custom reporter tried to require 'fs', but Mocha is not running in N
ode.js in mocha-phantomjs, so Node modules cannot be required - only other repor
ters
My dummmy html page looks like that:
<script type="text/javascript">
require.config({
baseUrl: '../app/',
paths: {
'app': '../app',
'specs': '../sampleTest/specs/',
'text': '../lib/require/text',
'durandal': '../lib/durandal/js',
'plugins' : '../lib/durandal/js/plugins',
'transitions' : '/lib/durandal/js/transitions',
'knockout': '../lib/knockout/knockout-2.3.0',
'jquery': '../lib/jquery/jquery-1.9.1'
}
});
var runTests = function (specfiles) {
// Initialize mocha and leak assert into the global space.
mocha.setup('bdd');
mocha.reporter('html');
assert = chai.assert;
require(specfiles, function () {
require(['specs/test.spec'],function(spec){
if (window.mochaPhantomJS) {
console.log('test with phantomJS')
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
});
};
runTests();
</script>
and my sample test looks like that:
define(['viewmodels/flickr'], function (flickr) {
describe('Flickr-Test', function(){
it('displayName should be equal to Flickr', function () {
assert.equal(flickr.displayName,'Flickr','should load right view model');
});
it('state should be pending', function () {
assert.equal(flickr.activate().state(),'pending','state should be pending');
});
});
describe("DOM Test", function () {
var el = document.createElement("div");
el.id = "myDiv";
el.innerHTML = "Hello World!";
document.body.appendChild(el);
var myEl = document.getElementById('myDiv');
it("has the right text", function () {
assert.equal(myEl.innerHTML,'Hello World!')
});
});
})
I haven't worked with mocha-phantomjs, but you might be hit by an issue that is described in http://durandaljs.com/documentation/Native-Apps-With-Node-Webkit.html
Next, because node has it's own implementation of require that is
different from require.js, which Durandal uses, we need to patch
things up a bit. To do that, add the following script block to the
head of your index.html:
<script type="text/javascript">
// this doesn't apply when not running with node webkit (nw)
// window.gui = require('nw.gui');
window.requireNode = window.require;
delete window.require;
window.requireNode.version = process.versions.node;
delete process.versions.node;
</script>

Resources