gulp.watch triggered twice on renaming file - javascript

Everytime I rename a file in srcDir, build-task get triggered twice, and they run concurrently too.
While the first build-task-instance run, the second instance clean-task triggered, causing weird errors and crash the gulp process entirely.
How can I stop this from happening ?
Here's the code:
// Clean task
gulp.task('clean', function () {
return gulp.src(dstDir)
.pipe(plugins.clean({ read: false }));
});
// Build task
gulp.task('build', ['clean'], function() {
gulp.src(srcDir)
.pipe(plugins.imagemin()) // Just for example, not neccessary exactly the same
.gulp.dest(dstDir);
});
// Watch task
gulp.task('watch', function() {
gulp.watch(srcDir, ['build']);
});
The plugin I used for cleaning is gulp-clean

Related

Can I gulp-notify when a watched task completes?

We have a gulpfile with ~12 tasks, 4 of which are activated by a gulp.watch. I would like to use gulp-notify when a task started by gulp.watch completes. I don't want gulp-notify to do anything if a task is run directly. Sample code below:
const
debug = require("gulp-debug"),
gulp = require("gulp"),
notify = require("gulp-notify");
gulp.task("scripts:app", function () {
return gulp.src(...)
.pipe(debug({ title: "tsc" }))
.pipe(...); // <--- if i add notify here,
// I will always get a notification
});
gulp.task("watch", function () {
gulp.watch("ts/**/*.ts", ["scripts:app"]);
});
If I pipe to notify inside the 'scripts:app' task, it will make a notification every time that task runs, regardless of how that task was started. Again, I want to notify when the watched task completes.
I considered adding a task 'scripts:app:notify' that depends on 'scripts:app', but if possible I'd like to avoid creating "unnecessary" tasks.
I also tried the following:
gulp.watch("ts/**/*.ts", ["scripts:app"])
.on("change", function (x) { notify('changed!').write(''); });
But that results in a notification for every file changed. I want a notification when the task completes.
In other words, if I run gulp scripts:app, I should not get a notification. When I run gulp watch and change a watched file, I should get a notification.
How can I do this?
Try adding params to your build script:
function buildApp(notify){
return gulp.src(...)
.pipe(...)
.pipe(function(){
if (notify) {
//drop notification
}
});
});
}
//Register watcher
gulp.watch("ts/**/*.ts", function(){
var notify = true;
buildApp(notify);
});
//Register task so we can still call it manually
gulp.task("scripts:app", buildApp.bind(null, false));
As you can see, buildApp is a simple function. It's callable through a watcher or a "normal" task registration.

Gulp tasks not working in sync

I'm trying to use browserify with babelify in my project. Everything works great except the problem of sync.
// Browserify
//---------------------------------------------------
gulp.task('browserify', function() {
var bundler = browserify('_babel/script.js').transform(babelify);
bundler.bundle()
.pipe(source('_babel/script.js'))
.pipe(gulp.dest('_dev'));
});
// JavaScript moving and merging
//---------------------------------------------------
gulp.task('js-min', ['browserify'], function() {
return gulp.src('_dev/_babel/script.js')
.pipe(concatjs('scripts.js'))
.pipe(gulp.dest('_js'))
.pipe(browserSync.stream());
});
gulp.watch('_babel/**', ['js-min']);
From what I can tell, browserify notifies gulp that it's done (it's done very quic, 10 ms or so) when it's not. And then js-min moves old file. Such observation seems valid because I am always one change behind.
What can I do?
There are three ways to tell Gulp that a task has finished.
You have all sync stuff to execute in the task:
gulp.task('task-a', function(){
// do sync stuff
// you may return here
// but because everything is sync Gulp assumes that everything has ended
});
You get the callback as input
// the passed cb is the next task to execute
gulp.task('task-b', function(cb){
// do async stuff
cb( result );
});
Return a promise/stream (which fits your case):
gulp.task('task-c', function(){
// return either a promise or a stream
return gulp.src( ... );
});
In both cases 2 and 3 Gulp will wait the end of the execution before calling the next function.
You are basically writing a case 3 but Gulp believes it's 1.
To fix this just return the bundler and you should be fine:
// Browserify
//---------------------------------------------------
gulp.task('browserify', function() {
var bundler = browserify('_babel/script.js').transform(babelify);
return bundler.bundle()
.pipe(source('_babel/script.js'))
.pipe(gulp.dest('_dev'));
});
// JavaScript moving and merging
//---------------------------------------------------
gulp.task('js-min', ['browserify'], function() {
return gulp.src('_dev/_babel/script.js')
.pipe(concatjs('scripts.js'))
.pipe(gulp.dest('_js'))
.pipe(browserSync.stream());
});
gulp.watch('_babel/**', ['js-min']);

Gulp watch, wait for task

I'd like to watch multiple files, when they change I'd like to run MsBuild and fire a reload with BrowserSync when the build is finished. So far I've got this "watcher":
gulp.watch([config.templatePath+'/**/*','!'+config.templatePath+'/assets/stylesheets/**/*'],['build']).on('change', function(file) {
browsersync.reload(file);
});
And this build task:
gulp.task('build', function() {
return gulp
.src(config.projectFile)
.pipe(msbuild({
toolsVersion: 12.0
}));
});
This is working fine, but the browser is reloaded before the build is finished. First I thought is was a problem with gulp-msbuild but I was forgotten the return, see: https://github.com/hoffi/gulp-msbuild/issues/8.
The build task is fired before the reload, but it's not waiting until it's completed. Any ideas how to fix this?
Thanks in advance!
you'll need a separate task for that, like build_reload:
gulp.task('build_reload', function() {
return gulp
.src(config.projectFile)
.pipe(msbuild({
toolsVersion: 12.0
}))
.on('end', function() {
browsersync.reload();
}));;
});
then change the watch task to:
gulp.watch([config.templatePath + '/**/*', '!' + config.templatePath + '/assets/stylesheets/**/*'], ['build_reload']);
this way it's only going to reload after everything finished.

Unsure about example given on BrowserSync homepage

Consider this example given on the BrowserSync + Gulp page regarding Browser Reloading, especially this part:
// use default task to launch BrowserSync and watch JS files
gulp.task('default', ['browser-sync'], function () {
// add browserSync.reload to the tasks array to make
// all browsers reload after tasks are complete.
gulp.watch("js/*.js", ['js', browserSync.reload]);
});
As task dependencies are run asynchronously (here: the js and browserSync.reload) couldn't it happen that the reload finishes before the js task?
Yes, according to the documentation, that's a possibility.
Off that same page...
(make sure you return the stream from your tasks to ensure the browser is reloaded at the correct time)
If it's an async task it will just fire and not return anything, and the watcher will not know to refresh. Or it may reload before the process is done.
To get around this, you should be adding callbacks to your tasks.
gulp.task('somename', function() {
var stream = gulp.src('client/**/*.js')
.pipe(minify())
.pipe(gulp.dest('build'));
return stream;
});
Just return the stream so Gulp knows what is up. Then set the watch for the task you want:
gulp.task('default', ['browser-sync'], function () {
// Watched tasks are run in parallel, not in series.
gulp.watch(['*.js'], ['somename', browserSync.reload]);
});
This is all included in the documentation:
https://github.com/gulpjs/gulp/blob/master/docs/API.md#async-task-support

Making gulp write files synchronously before moving on to the next task

gulpfile.js
gulp.task('browser-bundle', ['react'], function() {
...
});
gulp.task('react', function(){
gulp.src(options.JSX_SOURCE)
.pipe(react())
.pipe(gulp.dest(options.JSX_DEST))
});
As you can see I have the browser-bundle task depending on the react task. I believe this works as expected because in the output I see this:
[gulp] Running 'react'...
[gulp] Finished 'react' in 3.43 ms
[gulp] Running 'browser-bundle'...
However, although the react task is finished, the files its supposed to write to the operating system are not quite there yet. I've notice that if I put a sleep statement in the browser bundle command then it works as expected, however this seems a little hacky to me.
If I want the react task to not be considered finished until the files (from gulp.dest) have been synchronously written to disk how would I do that?
You need a return statement:
gulp.task('react', function(){
return gulp.src(options.JSX_SOURCE)
.pipe(react())
.pipe(gulp.dest(options.JSX_DEST))
});
With this all my write operations are done before the next task processed.
back to 2019: if some one come here with similar problem
In gulp 4.*, at least, gulp wait for promise to resolve but ignore the result.
so... if you use async await pattern and return the result of gulp.src('...') you got a surprise. the task not wait for stream finish before it continue! somthing that can result to serious bug and waist of time. the solution is "promisify" gulp.src
example:
gulp.task( async function notWaitingTask(){
// the return stream are ignored because function return promise not stream
return gulp.src('file.js')
.pipe(gulp.dest('new-location'))
})
gulp.task( async function waitingTask(){
// the return stream are respect
await promisifyStream(
gulp.src('file.js')
.pipe(gulp.dest('new-location'))
)
})
function promisifyStream(stream) {
return new Promise( res => stream.on('end',res));
}
The accepted answer is spot on, but as per https://github.com/gulpjs/gulp/issues/899, in the 3.x branch of gulp, you cannot do this with dependencies without a bit of extra special sauce:
var run = require('run-sequence');
var nodeunit = require('gulp-nodeunit');
var babel = require('gulp-babel');
var gulp = require('gulp');
/// Explicitly run items in order
gulp.task('default', function(callback) {
run('scripts', 'tests', callback);
});
/// Run tests
gulp.task('tests', function() {
return gulp.src('./build/**/*.tests.js').pipe(nodeunit());
});
// Compile ES6 scripts using bable
gulp.task('scripts', function() {
return gulp.src('./src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('./build'));
});
Notice specifically the use of the 'run-sequence' module to force the tasks to run one after another, as well.
(Without run, rm -rf build && gulp will result in OK: 0 assertions (0ms) because the tests task will not find the files created by the scripts task because it starts before the scripts task is completely resolved)
Met same issue here. Let's say there are 2 tasks, First and Second. Second runs after First.
The First task generates some files, which are to be read by the Second task. Using dependency doesn't make sure the Second task can find the files generated.
I have to explicitly using the done callback on the pipeline to let Second only starts after First truly done.
//This approach works!
gulp.task('First', function(done)) {
var subFolders = fs.readdirSync(somefolder)...
var tasksForFolders = subFolders.map(function(folder) {
return gulp.src('folder/**/*').sthtogeneratefiles();
});
tasksForFolders[tasksForFolders.length-1].on('end',done);
return tasksForFolders;
}
gulp.task('Second', ['First'],function() {
return gulp.src('generatedfolders/**/*').doth();
}
Without the done trick, the Second never finds the files generated by First. Below shows what I tried, the Second task can find the files generated by calling gulp First by hand, and then calling gulp Second subsequently.
//This is the WRONG approach, just for demonstration!!
gulp.task('First', function()) {
var subFolders = fs.readdirSync(somefolder)...
var tasksForFolders = subFolders.map(function(folder) {
return gulp.src('folder/**/*').sthtogeneratefiles();
});
return tasksForFolders;
}
gulp.task('Second', function() {
return gulp.src('generatedfolders/**/*').doth();
}

Categories