Dynamic loading mechanism of tasks (advanced)


Perhaps you have discovered that tmt-workflow all projects share only one copy node_modules, and all tasks are also defined in gulpfile.js Outside the _tasks directory, the implementation is actually very simple.

Let’s first look at gulpfile.js under the project

var gulp = require('gulp');
var fs = require('fs');
var path = require('path');

//注册
var deep = 3;
run_tasks('_tasks');

function run_tasks(tasks_path) {
    if (--deep < 0) {
        throw new Error('something wrong in require tasks!');
        return;
    }

    tasks_path = path.join('../', tasks_path);

    if (fs.existsSync(tasks_path)) {
        require(tasks_path)(gulp);
    } else {
        run_tasks(tasks_path);
    }
}

Every time a gulp task is executed, it will look up for the _tasks directory, which is defined here The level is 3, that is, gulpfile.js will search for 3 levels upwards, as long as _tasks is within these 3 levels. If your directory is very deep, just change 3 here. .

Then look at the index.js:

 fs.readdirSync(__dirname).filter(function (file) {
    return (file.indexOf(".") !== 0) && (file.indexOf('task') === 0);
}).forEach(function (file) {
    var registerTask = require(path.join(__dirname, file));
    registerTask(gulp, config);
});
in the

_tasks

directory. In fact, it is to load all the files in the current directory with task In the file at the beginning, we define each gulp task as a js file starting with task. In this way, all gulp tasks are dynamically registered and share a node_modules.