How to use gulp-watch? - gulp

What is the proper way to use gulp-watch plugin?
...
var watch = require('gulp-watch');
function styles() {
return gulp.src('app/styles/*.less')
.pipe(watch('app/styles/*.less'))
.pipe(concat('main.css'))
.pipe(less())
.pipe(gulp.dest('build'));
}
gulp.task('styles', styles);
I don't see any results when run gulp styles.

In your shell (such as Apple's or Linux's Terminal or iTerm) navigate to the folder that your gulpfile.js. For example, if you're using it with a WordPress Theme your gulpfile.js should be in your Theme's root. So navigate there using cd /path/to/your/wordpress/theme.
Then type gulp watch and hit enter.
If your gulpfile.js is configured properly (see example below) than you will see output like this:
[15:45:50] Using gulpfile /path/to/gulpfile.js
[15:45:50] Starting 'watch'...
[15:45:50] Finished 'watch' after 11 ms
Every time you save your file you'll see new output here instantly.
Here is an example of a functional gulpfile.js:
var gulp = require('gulp'),
watch = require('gulp-watch'),
watchLess = require('gulp-watch-less'),
pug = require('gulp-pug'),
less = require('gulp-less'),
minifyCSS = require('gulp-csso'),
concat = require('gulp-concat'),
sourcemaps = require('gulp-sourcemaps');
gulp.task('watch', function () {
gulp.watch('source/less/*.less', ['css']);
});
gulp.task('html', function(){
return gulp.src('source/html/*.pug')
.pipe(pug())
.pipe(gulp.dest('build/html'))
});
gulp.task('css', function(){
return gulp.src('source/less/*.less')
.pipe(less())
.pipe(minifyCSS())
.pipe(gulp.dest('build/css'))
});
gulp.task('js', function(){
return gulp.src('source/js/*.js')
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build/js'))
});
gulp.task('default', [ 'html', 'js', 'css', 'watch']);
Note: Anywhere you see source/whatever/ this is a path you'll either need to create or update to reflect the path you're using for the respective file.

gulp.task('less', function() {
gulp.src('app/styles/*.less')
.pipe(less())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function() {
gulp.watch(['app/styles/*.less'], ['less'])
});

Name your task like I have my 'scripts' task named so you can add it to the series. You can add an array of tasks to the series and they will be started in the order they are listed. For those coming from prior versions note the return on the gulp.src.
This is working code I hope it helps the lurkers.
Then (for version 4+) you need to do something like this:
var concat = require('gulp-concat'); // we can use ES6 const or let her just the same
var uglify = require('gulp-uglify'); // and here as well
gulp.task('scripts', function(done) {
return gulp.src('./src/js/*.js')
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/js/'));
});
gulp.task('watch', function() {
gulp.watch('./src/js/*.js',gulp.series(['scripts']))
});
** Note the line gulp.watch('./src/js/*.js',gulp.series(['scripts'],['task2'],['etc']))

Related

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 watch task sequence and Browser Sync

I am a new to using Gulp, just trying to learn it...Now the problem i get and want to ask is the way to setup default task with watch and browser sync included
I need to know am i doing something wrong
Can anybody improve my code here, i don't understand the relation of watch and browser sync, which tasks to run before browser-sync and when to watch
Below is my folder structure
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var uglify = require('gulp-uglify');
var less = require('gulp-less');
var plumber= require('gulp-plumber');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
var htmlmin = require('gulp-htmlmin');
var imagemin = require ('gulp-imagemin');
//scripts task
//uglifies
gulp.task('scripts', function(){
gulp.src('js/*.js')
.pipe(plumber())
.pipe(uglify())
.pipe(gulp.dest('build/js'));
});
//compress images
gulp.task('imagemin', function(){
gulp.src('img/**/*.+(png|jpg|gif|svg)')
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('build/img'));
});
//CSS styles
gulp.task('less', function(){
gulp.src('less/style.less')
.pipe(plumber())
.pipe(less())
.pipe(gulp.dest('build/css'));
});
gulp.task('cssmin', function(){
gulp.src('build/css/style.css')
.pipe(plumber())
.pipe(cssmin())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('build/css'))
.pipe(reload({stream:true})); // inject into browsers
});
gulp.task('htmlmin', function(){
return gulp.src('*.html')
.pipe(htmlmin({removeComments: true}))
.pipe(gulp.dest('build'))
.pipe(reload({stream:true})); // inject into browsers
});
// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
browserSync(['css/*.css', 'js/*.js','less/*.less', 'images/*'],{
server: {
baseDir: "./"
}
});
});
/* Watch scss, js and html files, doing different things with each. */
gulp.task('default', ['browser-sync' , 'scripts', 'less', 'cssmin', 'htmlmin', 'imagemin'], function () {
/* Watch scss, run the sass task on change. */
gulp.watch(['less/**/*.less'], ['less'])
//Watch css min
gulp.watch(['build/css/*.css'], ['cssmin'])
/* Watch app.js file, run the scripts task on change. */
gulp.watch(['js/*.js'], ['scripts'])
/* Watch .html files, run the bs-reload task on change. */
gulp.watch(['*.html'], ['htmlmin']);
// gulp.watch('app/*.html', browser-sync.reload);
// gulp.watch('app/js/**/*.js', browser-sync.reload);
});
Now the process i want is
Compile less to css and then minify it to build folder
List item
Then Minify my HTML code
Then minify and concatenate my js
Compress all the images (Run only when some images changes)
Run the minified HTML with Browser Sync and watch the changes in all my source HTML,Less, images and JS
I would not worry about minification at this point if your goal is to run in development mode, this applies for imagemin (i would do that offline anyways), cssmin, htmlmin, and your js task that runs uglify by default. Ideally you would want to debug in the browser, and having your code minified will not help you much. If you add a dist task to perform the minification step.
I understand that you need Less to CSS for obvious reasons. So you are looking for something like this:
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var browserSync = require('browser-sync').create();
var sass = require('gulp-less');
// Static Server + watching less/html files
gulp.task('serve', ['less'], function() {
browserSync.init({
server: "./"
});
gulp.watch("less/*.less", ['less']);
gulp.watch("*.html").on('change', browserSync.reload);
});
gulp.task('less', function(){
gulp.src('less/style.less')
.pipe(plumber())
.pipe(less())
.pipe(gulp.dest('build/css'))
.pipe(browserSync.stream());
});
gulp.task('default', ['serve']);
This code invokes serve as the main task. Serve task has less as a dependency (which is going to be invoked first). Then, the callback is finally invoked. BrowserSync is initialized and a watch is added for both html files and less files.
Check out this page if you want to learn more about gulp + browsersync integration.

Task 'sass' is not in your gulpfile

I've installed gulp and gulp-sass using npm.
Following the examples on github for gulp and gulp-sass I've created this simple gulpfile:
var gulp = require('gulp') ;
var sass = require('gulp-sass') ;
gulp.task('default', function() {
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
}) ;
If I run 'gulp' then nothing really happens - as expected. I get back
[00:20:20] Using gulpfile ~/wa/myproj/gulpfile.js
[00:20:20] Starting 'default'...
[00:20:20] Finished 'default' after 64 μs
That's all fine and dandy.
However, when I run 'gulp sass' I get back this:
[00:21:38] Using gulpfile ~/wa/myproj/gulpfile.js
[00:21:38] Task 'sass' is not in your gulpfile
[00:21:38] Please check the documentation for proper gulpfile formatting
I've clearly got a taks defined for 'sass'. What am I missing?
It probably didn't call because it was the function was inside default, and also default needs to call the other functions, after defining it outside default.
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function(){
gulp.src('./sass/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function(){
gulp.watch('./sass/**/*.scss',['sass']);
});
gulp.task('default', ['sass','watch']);
I figured it out:
The 'sass' task was wrapped inside the 'default' task.
This works:
var gulp = require('gulp') ;
var sass = require('gulp-sass') ;
gulp.task('default', function() {
}) ;
gulp.task('sass', function () {
gulp.src('./sass/**/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function () {
gulp.watch('./sass/**/*.scss', ['sass']);
});
I have faced the same issue "Task 'sass' is not in your gulpfile" when I use gulp scss command.
But when my friend ran gulp css command in command prompt, it worked properly by updating the CSS file. Please look at the below image, I hope this might help you.
var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function(){
gulp.src('./scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'));
});
gulp.task('watch', function(){
gulp.watch('./scss/**/*.scss',['sass']);
});
This works for me. Try it out. But I have to say My SASS folder's name is 'scss'. I changed the name and deleted the default task.

Gulp-minify-css does not produce output files

I have set up a very simple gulpfile.js There are only two task - 'sass' and 'minify-js'. These two tasks are fired by the task 'watch' when a change is detected. It all seems to be working well: Gulp is listening for changes, *.scss files are compiled into CSS, the console generates output as expected, without any errors. However, the CSS files do not get minified there are no output files from the 'minify-css' task whatsoever.
Why is 'minify-css' not working? What am I missing here?
This is my gulpfile.js:
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var minifyCSS = require('gulp-minify-css');
gulp.task('sass', function() {
gulp.src('plugins/SoSensational/styles/sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
gulp.task('minify-css', function() {
gulp.src('plugins/SoSensational/styles/dest/*.css')
.pipe(minifyCSS())
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
gulp.task('watch', function() {
gulp.watch('plugins/SoSensational/styles/sass/*.scss', ['sass', 'minify-css']);
});
Sounds like a race condition. Sass and MinifyCSS are executed in parallel, might be that your Sass task isn't done when you're already running MinifyCSS. Sass should be a dependency, so you have two options:
Make Sass a dependency from minifycss:
gulp.task('minify-css', ['sass'], function() {
return gulp.src('plugins/SoSensational/styles/dest/*.css')
.pipe(minifyCSS())
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
gulp.task('watch', function() {
gulp.watch('plugins/SoSensational/styles/sass/*.scss', ['minify-css']);
});
Have one task that does both!
gulp.task('sass', function() {
return gulp.src('plugins/SoSensational/styles/sass/*.scss')
.pipe(sass())
.pipe(minifyCSS())
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
The latter one is actually the preferred version. You save yourself a lot of time if you don't have an intermediate result
Btw: Don't forget the return statements
I know this is kind of an old question but thought I'd throw this out there because it's something that's helped me. To build on the answer from ddprrt, I'd recommend changing:
gulp.task('sass', function() {
return gulp.src('plugins/SoSensational/styles/sass/*.scss')
.pipe(sass())
.pipe(minifyCSS())
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
to:
var rename = require('gulp-rename');
gulp.task('sass', function() {
return gulp.src('plugins/SoSensational/styles/sass/*.scss')
.pipe(sass('site.css'))
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'))
.pipe(minifyCSS())
.pipe(rename('site.min.css'))
.pipe(gulp.dest('plugins/SoSensational/styles/dest/'));
});
This allows you to debug with the un-minified CSS and deploy the minified version.
It's because the gulp-minify-css is deprecated. Use gulp-clean-css instead.
Click here(https://www.npmjs.com/package/gulp-minify-css "npm-clean-css")!

gulp-watch doesn't update gulp-jshint

what's wrong with this code:
var gulp = require('gulp');
var watch = require('gulp-watch');
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
//lint
module.exports = gulp.task('lint', function () {
return gulp.src([config.paths.src.scripts,config.paths.exclude.bower])
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
//watch
module.exports = gulp.task('watch', function () {
watch(config.paths.src.scripts, ['lint'])
.pipe(connect.reload());
watch(config.paths.src.templates, ['templates'])
.pipe(connect.reload());
watch(config.paths.src.index)
.pipe(connect.reload());
});
when ie I edit a js file doing an error
jshint show me nothing.
This works:
watch(config.paths.src.scripts)
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(connect.reload());
but it's quite the same or not ?
gulp-watch does not support an array of task names like the internal gulp.watch. See documentation at https://www.npmjs.org/package/gulp-watch
You have to provide gulp-watch a function, something like
watch(config.paths.src.scripts, function(events, done) {
gulp.start(['lint'], done);
}
Note: It seems that gulp.start will be deprecated in Gulp 4.x, it will be replaced by a task runner called bach: https://github.com/floatdrop/gulp-watch/issues/92