cschuff
cschuff

Reputation: 5542

Task inheritance in gulp, parent gulpfile.js

I am using node/gulp to run/build my projects. Accross those projects my gulpfiles look very similar. Since I'm coming from a Java/Maven background I was looking for sth. like a parent gulpfile one could inherit basic tasks from (this is easily possible with a parent pom.xml in maven).

Is this somehow build into gulp, are there modules doing this or do I need to figure this myself?

I could think of having a node module doing nothing else then providing basic gulp tasks that one can require from his dependent gulp file. Any experiences on an approach like this?

BR Chris

Upvotes: 2

Views: 1582

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30574

You could just export the gulp object in your parent gulpfile and then require it in the child gulpfiles:

project/gulpfile.js:

var gulp = require('gulp');

gulp.task('commontask', function () { });

module.exports = gulp;

project/subproject/gulpfile.js:

var gulp = require('../gulpfile.js');

gulp.task('subtask', [ 'commontask' ], function() { });

Running subtask from the project/subproject directory:

> gulp subtask
[12:38:05] Using gulpfile ~/project/subproject/gulpfile.js
[12:38:05] Starting 'commontask'...
[12:38:05] Finished 'commontask' after 50 μs
[12:38:05] Starting 'subtask'...
[12:38:05] Finished 'subtask' after 20 μs

EDIT: The above won't work if the parent gulpfile isn't part of the same package (e.g. my-app) but rather from another package that you depend on (e.g. my-common-tasks). The reason is that the way module loading in Node.js works, you end up with two instances of gulp: one in my-common-tasks and one in my-app. Your tasks will be defined in the instance from my-common-tasks, but the gulp CLI will look for the tasks in the instance from my-app.

Instead you have to pass the gulp instance from my-app to my-common-tasks:

my-common-tasks/gulpfile.js:

module.exports = function(gulp) {
  gulp.task('common-task', function () { });
};

my-app/gulpfile.js:

var gulp = require('gulp');
require('my-common-tasks')(gulp);

gulp.task('sub-task', [ 'common-task' ], function() { });

Upvotes: 4

Related Questions