跳到主要内容

tree()

获取当前任务依赖关系树的 JSON 表示。任务依赖关系树中存储的函数被规范化为字符串以便于序列化。

用法

const { tree, series, parallel } = require('gulp');

function clean(cb) {
cb();
}

function css(cb) {
cb();
}

function javascript(cb) {
cb();
}

exports.build = series(clean, parallel(css, javascript));

tree();
// 输出: { label: 'Tasks', nodes: [ { label: 'build', type: 'task', nodes: [ ... ] } ] }

tree({ deep: false });
// 输出: { label: 'Tasks', nodes: [ { label: 'build', type: 'task' } ] }

tree({ deep: true });
// 输出: { label: 'Tasks', nodes: [ { label: 'build', type: 'task', nodes: [ ... ] } ] }

输出格式如下:

{
label: "Tasks",
nodes: [
{
label: "build",
type: "task",
nodes: [
{
label: "<series>",
type: "function",
branch: true,
nodes: [
{
label: "clean",
type: "function"
},
{
label: "<parallel>",
type: "function",
branch: true,
nodes: [
{
label: "css",
type: "function"
},
{
label: "javascript",
type: "function"
}
]
}
]
}
]
}
]
}

签名

tree([options])

参数

参数类型说明
optionsobject选项,用于确定任务树的显示方式。传入 { deep: false } 以获取顶级任务列表。

返回值

一个格式化为节点和嵌套节点树的对象,可以用于将任务层次结构可视化。

选项参数(可选)

默认情况下,任务树的内容是完整的树,展示所有任务及其依赖关系(相当于 { deep: true })。如果只需要顶级任务,可以传递 { deep: false } 选项,以获取顶级任务的平面列表。每个输出的节点对象都会有一个 label 字段,用于显示任务名称。

每个根级节点对象还将有一个 type 字段来标识该节点是什么类型(例如 'task')。

具有依赖的根级节点将有一个 nodes 字段,其中包含由依赖表示的更多节点对象。表示像 series()parallel() 这样的组合的节点将有一个 branch 字段,设置为 true

tree({ deep: false });
// 输出:
// {
// label: "Tasks",
// nodes: [
// {
// label: "build",
// type: "task"
// }
// ]
// }

示例

下面的示例将使用 archy 模块格式化树,以便以更加完整且易于阅读的方式打印到控制台:

const { tree, series, parallel } = require('gulp');
const archy = require('archy');

function clean(cb) {
cb();
}

function css(cb) {
cb();
}

function javascript(cb) {
cb();
}

exports.build = series(clean, parallel(css, javascript));

const output = JSON.stringify(tree({ deep: true }));
console.log(archy(JSON.parse(output)));
// 输出:
// Tasks
// └─┬ build
// └─┬ <series>
// ├── clean
// └─┬ <parallel>
// ├── css
// └── javascript