Can I pass arguments to a gulp task?

混江龙づ霸主 提交于 2020-01-02 23:28:32

问题


I'm using gulp in Visual Studio, as a client-side build tool only.

I have lots of tasks which are common across various projects, so I moved them to separate files, and reference them in a project's gulpfile.js as follows:

require("../path/to/task/files/fooCommon.js");  // has a task called "fooCommon"

And then in the gulpfile.js I wrap it in a task:

gulp.task("foo", ["fooCommon"], function () { });

This works nicely, and I can reuse common tasks across projects.

BUT, some tasks require configurations which are only accessible in gulpfile.js - how can I pass them as arguments to a task?


回答1:


Two things come to mind. The first would be that instead of fooCommon.js creating tasks, it could create something usable as a gulp plugin, so then to use it, you just pass your config arguments to the plugin. If that doesn't fit well in this case, then you can move your task logic into a wrapper function, e.g.

fooCommon.js

module.exports = function(gulp, config){
    gulp.task("fooCommon", function () {
        // Use the config here
    });
};

Gulpfile

// Define whatever config you need
var gulp = require('gulp');

var config = {...}

var taskCreator = require('../path/to/task/files/fooCommon.js');

// Call the function in 'fooCommon.js', which will be passed the config, and
// will create all the tasks you have in common.
taskCreator(gulp, config);

// Register a task depending on the task created by the exported function.
gulp.task("foo", ["fooCommon"], function () { });


来源:https://stackoverflow.com/questions/27306844/can-i-pass-arguments-to-a-gulp-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!