Search code examples
javascriptnode.jsgulp

Run a specific task when the task required by user is not present in the gulpfile


Is there any way to run a specific task when the task supplied by the user is not present in the gulpfile.

For example, if the user runs gulp build and the build task is not there in the gulpfile then a specific task (or default task, doesn't matter to me) should run.

As an analogy, consider the specified task as the 404 page for gulp.


Solution

  • gulp inherits from orchestrator, which contains a tasks instance variable that is a plain object with keys that are names of tasks added to the instance. If you replaced tasks with a proxy, you could have it return a default task, like default by using the get trap handler:

    const gulp = require('gulp')
    
    gulp.tasks = new Proxy(gulp.tasks, {
      get (target, property) {
        if (target.hasOwnProperty(property)) {
          return target[property]
        }
    
        return target.default
      }
    })
    

    That code can be run at anytime before the sequence of tasks is started, even after some tasks have already been added to the gulp instance.