Gulp 4 - watch not watching changes - javascript

Today I migrated to Gulp 4, but I'm not able to get my watch function to work.
// Watch
gulp.task('watch', gulp.series('typescript', 'sass', 'browserSync', function(){
gulp.watch('./app/styles/**/*.scss', gulp.series('sass'));
gulp.watch('app/scripts/**/*.ts', gulp.series('typescript'));
gulp.watch('./app/*.html', browserSync.reload);
}));
typescript, sass, browserSync will run but watch does not react to file changes.

I just had the same problem. You don't actually have a reference to the initialized browserSync inside your watch gulp task. Instead of having your browserSync.init function in a separate browserSync gulp task, move it to inside your watch task, and it should work. Hope this helps!
Example:
gulp.task('watch', gulp.series(function (){
browserSync.init({
proxy:"http://localhost:8888",
injectChanges: true,
plugins: ["bs-html-injector?files[]=*.html"]
});
var html = gulp.watch('development/index.html');
html.on('change', function(path, stats) {
console.log('you changed the html');
browserSync.notify("Compiling, please wait!");
browserSync.reload("index.html");
})
var js = gulp.watch('development/**/*.js');
js.on('change', function(path, stats) {
console.log('you changed the js');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
var css = gulp.watch('development/**/*.css');
css.on('change', function(path, stats) {
console.log('you changed the css');
browserSync.notify("Injecting CSS!");
browserSync.reload("*.css");
})
}));

Change gulp.watch('app/scripts/**/*.ts', gulp.series('typescript')); to a absolute gulp.watch('./app/scripts/**/*.ts', gulp.series('typescript'));
Also i normally stick this syntax, per task.
var watcher = gulp.watch('js/**/*.js', gulp.parallel('concat', 'uglify'));
watcher.on('change', function(path, stats) {
console.log('File ' + path + ' was changed');
});

I had some issues too, and i found this tutorial of gulp 4, this is my gulpfile to compile scss and watch the Scss files, concat and compile to a main.min.css with autoprefix.
var gulp = require('gulp'),
concat = require('gulp-concat'),
autoprefixer = require('gulp-autoprefixer'),
sass = require('gulp-sass');
//task para o sass
var paths = {
styles: {
src: 'scss/**/*.scss',
dest: 'css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(concat('main.min.css'))
.pipe(autoprefixer({
browser: ['last 2 version', '> 5%'],
cascade: false
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp.watch(paths.styles.src, styles);
}
var build = gulp.parallel(styles, watch);
gulp.task(build);
gulp.task('default', build);
I think that on the gulp v4 you need to use the gulp.parallel. I'm digging to learn more about the new version.

Related

Gulp 4 Sass + BrowserSync Injection with MAMP

I've spent the whole day trying to figure this out right. I am aware of
Gulp 4 & BrowserSync: Style Injection?
and tried different approaches to this. What am I missing?
I am trying to get gulp to inject the sass generated style to the browser. As of now, it does open a new tab with the generated css, but it does neither refresh nor inject the newly generated style when changing. I get:
[Browsersync] Watching files...
[21:27:36] Starting 'buildStyles'...
[21:27:36] Finished 'buildStyles' after 40 ms
[Browsersync] File event [change] : site/templates/styles/main.css
But it doesn't inject. Here's my gulpfile.js:
const { src, dest, watch, series, parallel } = require('gulp');
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const paths = {
sass: {
// By using styles/**/*.sass we're telling gulp to check all folders for any sass file
src: "site/templates/styles/scss/*.scss",
// Compiled files will end up in whichever folder it's found in (partials are not compiled)
dest: "site/templates/styles"
},
css: {
src: "site/templates/styles/main.css"
}
};
function buildStyles(){
return src(paths.sass.src)
.pipe(sass())
.on("error", sass.logError)
.pipe(dest(paths.sass.dest))
}
function watchFiles(){
watch(paths.sass.src,{ events: 'all', ignoreInitial: false }, series(buildStyles));
}
function browserSync(done){
browsersync.init({
injectChanges: true,
proxy: "http://client2019.local/",
port: 8000,
host: 'client2019.local',
socket: {
domain: 'localhost:80'
},
files: [
paths.css.src
]
});
done();
// gulp.watch("./**/*.php").on("change", browserSync.reload);
}
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles;
exports.watch = watchFiles;
exports.build = series(buildStyles); // $ gulp build
What am I missing?
I don't know if I fully understand what are you want.
To auto refresh the browser with BrowserSync, after saving your last changes, I'm using this code on my gulp file:
var paths = {
styles: {
src: "./src/styles/scss/**/*.scss",
dest: "./view/styles"
},
htmls: {
src: "./src/**/*.html",
dest: "./view"
}
};
const styles= () => {
return...
}
const html= () => {
return...
}
const watch = () => {
browserSync.init({
server: {
baseDir: "./view"
}
});
gulp.watch(paths.styles.src, style);
gulp.watch(paths.htmls.src, html);
gulp.watch("src/**/*.html").on('change', browserSync.reload);
};
exports.style = style;
exports.html = html;
exports.watch = watch;
var build = gulp.parallel(style, html, watch);
gulp.task('default', working);
Then I just execute gulp for build and watch with auto reload.

Gulp sass watch create new css folder

Ihave 2 problems with gulp sass watch
1- when i save my sass file gulp create extra css folder and i already have one
2- gulp watch is only watching for my style.scss and not the other files inside the other folders
My project structure
assets
css
style.css
sass
1-basics
_base.scss
_colors.scss
2-layout
_grid.scss
_header.scss
style.scss
index.html
gulp
const gulp = require('gulp');
const watch = require('gulp-watch');
const sass = require('gulp-sass');
const bs = require('browser-sync').create();
gulp.task('browser-sync', ['sass'], function() {
bs.init({
server: {
baseDir: "./"
}
});
});
gulp.task('sass', function () {
return gulp.src('assets/sass/**/*style.scss')
.pipe(sass())
.pipe(gulp.dest('./assets/css'))
.pipe(bs.reload({stream: true}));
});
gulp.task('watch', ['browser-sync'], function () {
gulp.watch("assets/sass/**/*style.scss", ['sass']);
gulp.watch("*.html").on('change', bs.reload);
});
I modified a few parts of your code, see the comments:
const gulp = require('gulp');
// you are not using the following require, gulp.watch is not the watch plugin below
// it is a function of the gulp object required above
// const watch = require('gulp-watch');
const sass = require('gulp-sass');
const bs = require('browser-sync').create();
gulp.task('browser-sync', ['sass'], function() {
bs.init({
server: {
baseDir: "./"
}
});
// note I moved the watch tasks to within the browser-sync task
// and changed the sass watch glob below
// so it watches both the partials and style.scss
gulp.watch("assets/sass/**/*.scss", ['sass']);
gulp.watch("*.html").on('change', bs.reload);
});
gulp.task('sass', function () {
// this appears to be the correct path to your style.scss file
return gulp.src('assets/style.scss')
.pipe(sass())
// with the change to the gulp.src above, now the gulp.dest is correct
// before you had a globstar ** and that effects the base directory
// that will be used below. Without the globstar it is a little easier
.pipe(gulp.dest('./assets/css'))
.pipe(bs.reload({stream: true}));
});
// moving the watch tasks now allows this simple default task
gulp.task('default', ['browser-sync']));
// below not needed now
//gulp.task('watch', ['browser-sync'], function () {
//gulp.watch("assets/sass/**/*style.scss", ['sass']);
//gulp.watch("*.html").on('change', bs.reload);
//});

gulpfile.js - task is not in gulp file error

Below is my current Gulpfile.js and when I'm attempting to run gulp minify I'm getting the error, "Task 'minify' is not in your gulpfile". However, I'm able to run gulp sass with no issues. I also have each module installed with npm.
module.exports = function(gulp) {
'use strict'
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var cssnano = require('gulp-cssnano');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('minify', function() {
return gulp.src('app/css/**/*.css')
.pipe(cssnano())
.pipe(concat('style.min.css'))
.pipe(gulp.dest('app/css/min'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('watch', ['browserSync', 'sass', 'cssnano'], function() {
gulp.watch('app/scss/**/*.scss', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
});
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app/'
},
})
})
}
You should not treat the gulpfile.js as a node module and drop the following part
module.exports = function(gulp) {
(don't forget to remove the closing curly (}) at the end of the gulpfile.js)
Then, you should require gulp
var gulp = require('gulp');
That should make it run smoothly.
Why it does run your gulp sass, I don't know. I just created a simple test file in a fresh directory, and it didn't recognise the sass task for me. Maybe you installedgulp, sass or both globally at some point (e.g. earlier project).

Gulp livereload not working in Chrome

So I am trying to set up the livereload server, however, I never get the message Live reload server listening on: <port_number> like in this video. If I change my files, the console says that the file was reloaded. I have the Chrome extension installed. What am I missing? Thanks.
gulpfile.js
'use strict';
// include gulp
var gulp = require('gulp'),
gutil = require('gulp-util');
// include plug-ins
var autoprefix = require('gulp-autoprefixer'),
changed = require('gulp-changed'),
concat = require('gulp-concat'),
http = require('http'),
imagemin = require('gulp-imagemin'),
jshint = require('gulp-jshint'),
livereload = require('gulp-livereload'),
minifyCSS = require('gulp-minify-css'),
minifyHTML = require('gulp-minify-html'),
sass = require('gulp-sass'),
st = require('st'),
stripDebug = require('gulp-strip-debug'),
uglify = require('gulp-uglify');
gulp.task('build-css', function() {
return gulp.src('src/scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/styles'));
});
// minify new or changed HTML pages
gulp.task('htmlpage', function() {
var htmlSrc = './src/*.html',
htmlDst = './dist';
return gulp.src(htmlSrc)
.pipe(changed(htmlDst))
.pipe(minifyHTML())
.pipe(gulp.dest(htmlDst));
});
// minify new images
gulp.task('imagemin', function() {
var imgSrc = './src/images/**/*',
imgDst = './dist/images';
return gulp.src(imgSrc)
.pipe(changed(imgDst))
.pipe(imagemin())
.pipe(gulp.dest(imgDst));
});
// JS hint task
gulp.task('jshint', function() {
return gulp.src('./src/scripts/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// JS concat, strip debugging and minify
gulp.task('scripts', function() {
return gulp.src(['./src/scripts/lib.js','./src/scripts/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./dist/scripts/'));
});
gulp.task('server', function(done) {
http.createServer(
st({
path: __dirname + '/dist',
index: 'index.html',
cache: false
})
).listen(8080, done);
});
// CSS concat, auto-prefix and minify
gulp.task('styles', function() {
return gulp.src(['./src/styles/*.css'])
.pipe(concat('styles.css'))
.pipe(autoprefix('last 2 versions'))
.pipe(minifyCSS())
.pipe(gulp.dest('./dist/styles/'));
});
gulp.task('watch', ['server'], function() {
livereload.listen({
basePath: 'dist'
});
// watch for HTML changes
gulp.watch('./src/*.html', ['htmlpage']).on('change', livereload.changed);
// watch for JS changes
gulp.watch('./src/scripts/*.js', ['jshint', 'scripts']).on('change', livereload.changed);
// watch for CSS changes
gulp.watch('./src/styles/*.css', ['styles']).on('change', livereload.changed);
gulp.watch('src/scripts/**/*.js', ['jshint']).on('change', livereload.changed);
gulp.watch('src/styles/scss/**/*.scss', ['build-css']).on('change', livereload.changed);
});
// default gulp task
gulp.task('default', ['imagemin', 'htmlpage', 'scripts', 'styles', 'watch'], function() {
return gutil.log('Gulp is running!')
});
I use browser-sync to reload the browser when a file has changed.
Try something like this:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('serve', function() {
gulp.watch("app/**/*.js").on('change', browserSync.reload);
gulp.watch("templates/**/*.html").on('change', browserSync.reload);
gulp.watch("css/**/*.css").on('change', browserSync.reload);
browserSync.init({
server: "./"
});
});
gulp.task('default', ['serve']);
I recommend your attention to the real-time browser page reload tool.
Live Reload Browser Page
Live Reload Browser Page
GitHub
Easy to use. Works independently of the IDE. But you need the IDE to be able to auto-save files. Also works with tools like Gulp, WebPack, Grunt and others.

Browsersync not syncing scroll

I am new to gulp and I'm trying to get browser-sync working. It seems to work fine except that the syncronised scroll is not working. Can anyone see what might be wrong with my setup.
var gulp = require('gulp'),
jade = require('gulp-jade'),
uglify = require('gulp-uglify'),
gutil = require('gulp-util'),
sass = require('gulp-sass'),
livereload = require('gulp-livereload'),
browserSync = require('browser-sync');
var outputDir = "builds/development";
gulp.task('jade', function() {
return gulp.src('src/templates/**/*.jade')
.pipe(jade())
.pipe(gulp.dest(outputDir))
.pipe(livereload());
});
// Js - to uglify use gulp js --type production ( or just leave out js to build everything )
gulp.task('js', function() {
return gulp.src('src/js/main.js')
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(gulp.dest(outputDir + '/js'))
.pipe(livereload());
});
// Sass - to compress use gulp sass --type production ( or just leave out sass to build everything )
gulp.task('sass', function() {
var config = {};
if ( gutil.env.type === 'production') {
config.outputStyle = 'compressed';
}
return gulp.src('src/sass/main.scss')
.pipe(sass(config))
.pipe(gulp.dest(outputDir + '/css'))
.pipe(livereload());
});
// Browser Sync ( not working 100% ... not scrolling )
gulp.task('browser-sync', function() {
browserSync({
proxy: "http://localsandbox.dev/gulptutorial/builds/development/"
});
});
// Watch
gulp.task('watch', function() {
gulp.watch('src/templates/**/*.jade', ['jade']);
gulp.watch('src/js/**/*.js', ['js']);
gulp.watch('src/sass/**/*.scss', ['sass']);
});
gulp.task('default', ['jade', 'js', 'sass', 'watch', 'browser-sync'], function () {
gulp.watch("js/*.js", ['js', browserSync.reload]);
});
Your issue might be related to watching with both Gulp and BrowserSync. Here is a good reference to that:
"You shouldn't watch files with BrowserSync + Gulp" https://github.com/shakyShane/gulp-browser-sync/issues/16#issuecomment-43597240
So you would probably want remove livereload (let BrowserSync handle everything) and change your default Gulp task to something like this:
gulp.task('default', ['jade', 'js', 'sass', 'browser-sync'], function () {
gulp.watch('src/templates/**/*.jade', ['jade', browserSync.reload]);
gulp.watch('src/js/**/*.js', ['js', browserSync.reload]);
gulp.watch('src/sass/**/*.scss', ['sass', browserSync.reload]);
});
You could also try setting scroll explicitly (but it defaults to true anyway):
gulp.task('browser-sync', function() {
browserSync({
proxy: "http://localsandbox.dev/gulptutorial/builds/development/"
ghostMode: {
scroll: true
}
});
});
I had the same problem and that was because I had a javascript function called scrollTo declared in my own code, which was interfering with browserSync code. All I needed to do is to rename that function, and the browsersync scrolling was working again.

Categories