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']);
Related
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
I need my gulp tasks to be synchronous (process JS and CSS async, but only after those are completed process HTML since it contains inline JS and CSS), and while plugins like gulp-run-sequence have been immensely useful, I still need to structure my tasks correctly in a way that they can be marked as completed.
Take for example;
gulp.task('process-css', function() {
return gulp.src(['src/app.scss'])
.pipe(gp.plumber())
.pipe(gp.sass().on('error', gp.sass.logError))
.pipe(gp.autoprefixer())
.pipe(gp.cleanCSS())
.pipe(gp.rename('app.min.scss'))
.pipe(gulp.dest('./app'));
});
Because I'm doing the return gulp.src()... which returns the executing gulp stream, both gulp-run-sequence and gulp can know my task is finished when it reaches the final .pipe()...
But what if I have something like this:
gulp.task('process-css-debug', function() {
gulp.src('src/**/app.scss')
.pipe(gp.plumber())
.pipe(gp.sass().on('error', gp.sass.logError))
.pipe(gp.autoprefixer())
.pipe(gp.rename('app.min.scss'))
.pipe(gulp.dest('./app'));
return gulp.src('src/**/app.inline.scss')
.pipe(gp.plumber())
.pipe(gp.sass().on('error', gp.sass.logError))
.pipe(gp.autoprefixer())
.pipe(gp.rename('app.inline.min.scss'))
.pipe(gulp.dest('./app'));
});
Because I'm now in need of running two gulp streams at once, I can't possibly do a double return of both of them so the task can be marked as completed until both of them streams are. My only solutions right now are:
Separating the streams into 2 separate gulp tasks
Running the second stream inside a function that's inside the first streams's last .pipe()
Is there a more elegant way to do this? Also, I can't process all the CSS in one stream because I need to be able to individually rename each SASS file.
You can use merge-stream or event-stream packages.
Here is example for merge-stream:
var merge = require('merge-stream');
gulp.task('process-css-debug', function() {
var first = gulp
.src('src/**/app.scss')
.pipe(gp.plumber())
.pipe(gp.sass().on('error', gp.sass.logError))
.pipe(gp.autoprefixer())
.pipe(gp.rename('app.min.scss'))
.pipe(gulp.dest('./app'));
var second = gulp
.src('src/**/app.inline.scss')
.pipe(gp.plumber())
.pipe(gp.sass().on('error', gp.sass.logError))
.pipe(gp.autoprefixer())
.pipe(gp.rename('app.inline.min.scss'))
.pipe(gulp.dest('./app'));
return merge(first, second);
});
I have this task:
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var svgSprite = require("gulp-svg-sprites");
var clean = require('gulp-clean');
gulp.task('sprite-make', function () {
//first task
gulp.src([path.join(conf.paths.src, '/assets/svg/*.svg'), '!' + path.join(conf.paths.src, '/assets/svg/sprite.svg')])
.pipe(svgSprite({
preview: false,
svgPath: path.join(conf.paths.src, '/assets/svg/sprite.svg'),
cssFile: ('_sprite.scss')
}))
.pipe(gulp.dest(path.join(conf.paths.src, '/app/styles')));
//second task
gulp.src(path.join(conf.paths.src, '/app/styles/svg/**/*'))
.pipe(gulp.dest(path.join(conf.paths.src, '/assets/svg')));
//third task
gulp.src(path.join(conf.paths.src, '/app/styles/svg'), {read: false})
.pipe(clean());
});
What I want is to execute this tasks one after another (create the sprite -> copy it to new destination -> delete the src).
Currently the tasks running async, and if I try to do pipe(gulp.src(...) I am getting the following error: Unhandled stream error in pipe
Pretty well defined in the doc : https://github.com/gulpjs/gulp/blob/master/docs/API.md
Note: By default, tasks run with maximum concurrency -- e.g. it
launches all the tasks at once and waits for nothing. If you want to
create a series where tasks run in a particular order, you need to do
two things:
give it a hint to tell it when the task is done, and give it a hint
that a task depends on completion of another. For these examples,
let's presume you have two tasks, "one" and "two" that you
specifically want to run in this order:
In task "one" you add a hint to tell it when the task is done. Either
take in a callback and call it when you're done or return a promise or
stream that the engine should wait to resolve or end respectively.
In task "two" you add a hint telling the engine that it depends on
completion of the first task.
So this example would look like this:
var gulp = require('gulp');
// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
// do stuff -- async or otherwise
cb(err); // if err is not null and not undefined, the run will stop, and note that it failed
});
// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
// task 'one' is done now
});
gulp.task('default', ['one', 'two']);
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
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();
}