如何在Gulp 4中将功能作为任务运行?

时间:2018-10-27 10:21:37

标签: javascript gulp gulp-4

如何在执行Gulp的过程中运行功能,以便Gulp将功能视为任务(将其打印到日志中)?

这是我的gulpfile.js的示例:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  // Some asynchronous logic which gets the subtasks
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await subTask(); // I want it to run as a Gulp task
  }));
};

预期的Gulp输出:

Starting 'default'...
Starting 'todo «foo»'...
Starting 'todo «bar»'...
Finished 'todo «foo»' after 1.2s
Finished 'todo «bar»' after 1.5s
Finished 'default' after 2s

实际Gulp输出:

Starting 'default'...
Finished 'default' after 2s

为什么:我的子任务列表无法同步获取,并且Gulp doesn't support asynchronous configuration也将不支持它。但是我仍然希望在Gulp输出中看到子任务的进度和计时。

1 个答案:

答案 0 :(得分:0)

将该函数包装到gulp.seriesgulp.parallel中,以使Gulp显示其状态。看起来这不是一个优雅的解决方案,但这是我发现的最好的解决方案。

这是一个通用示例:

function runGulpTask(func) {
  return new Promise((resolve, reject) => gulp.series(func)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));

  // The same solution using built-in Node.js functions:
  // const {promisify} = require('util');
  // return promisify(gulp.series(func))();
}

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  await Promise.all(todos.map(async todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    await runGulpTask(subTask);
  }));
};

Gulp输出与预期输出相同。

这是一个更具体的示例:

async function doStaff(todo) {
  // ...
}

exports.default = async () => {
  const todos = await myAPI.getTodos();

  const subTasks = todos.map(todo => {
    const subTask = doStuff.bind(todo);
    subTask.displayName = `todo «${todo.name}»`;
    return subTask;
  });

  await new Promise((resolve, reject) => gulp.parallel(...subTasks)(error => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  }));
  // Or using built-in Node.js functions:
  // const {promisify} = require('util');
  // await promisify(gulp.parallel(...subTasks))();
};