Significant amount of time taken by running Gulp task falls on such things like:
This can be optimized if instead of running each time gulp task_name
we will run something that will load gulpfile.js
and start prompt where we can run gulp task by entering its name. This will allow to spend time on loading gulp tasks only once and imported node modules will be cached by require
and loaded much faster on subsequent task executions.
How can this be implemented?
This is self-answered question where I share my knowledge with community.
Other answers are welcome. Best answer will be accepted.
UPDATE:
I published npm package gulp-interactive.
Just install it with:
npm install --save-dev gulp-interactive
And use it in gulpfile.js
:
require('gulp-interactive')();
Then in shell:
$ gulp prompt
ORIGINAL ANSWER:
I implemented special gulp task prompt
.
First install inquirer:
npm install --save-dev inquirer
It's a useful package that will allow us to ask developer to enter task name.
Next implement the task:
gulp.task('prompt', function (cb) {
var promptedTask;
function startPrompt() {
promptedTask = undefined;
gulp.start('prompt');
}
function onTaskEnd(event) {
setTimeout(function () {
if (event && promptedTask && event.task === promptedTask) {
gulp.removeListener('task_stop', onTaskEnd);
gulp.removeListener('task_err', onTaskEnd);
gulp.removeListener('task_not_found', onTaskEnd);
startPrompt();
}
});
}
gulp.on('task_stop', onTaskEnd);
gulp.on('task_err', onTaskEnd);
// replace gulp default listener for 'task_not_found' because it calls process.exit(1)
gulp.removeAllListeners('task_not_found');
gulp.on('task_not_found', function (err) {
console.log('Task \'' + err.task + '\' is not in your gulpfile');
onTaskEnd(err);
});
var inquirer = require('inquirer');
inquirer.prompt([{ type: 'input', name: 'task', 'message': 'Enter gulp task name:' }])
.then(function (answers) {
promptedTask = answers.task || 'prompt';
cb();
gulp.start(promptedTask);
});
});
Now you can launch prompt by executing gulp prompt
.
Using this optimization reduced build time for my web application from 50 to 15 seconds inside my Docker for Mac container (I believe that's because of slow filesystem operations). When running build directly on my Mac build time was reduced from 13 to 6 seconds.