path.json
{
"plguin_a_name": {
"css": {
"src/plugin_a/1.css": "dist/plugin_a/1.css",
"src/plugin_a/2.css": "dist/plugin_a/2.css"
},
"js": {
"src/plugin_a/1.js": "dist/plugin_a/1.js",
"src/plugin_a/2.js": "dist/plugin_a/2.js"
}
},
"plugin_b_name": {
"css": {
"src/plugin_b/1.css": "dist/plugin_b/1.css",
"src/plugin_b/2.css": "dist/plugin_b/2.css"
},
"js": {
"src/plugin_b/1.js": "dist/plugin_b/1.js",
"src/plugin_b/2.js": "dist/plugin_b/2.js"
}
}
}
如何从gulp中的这个json文件循环,将每个插件从src复制到dist并返回?
我想完成两个任务,只循环css / js或循环“plugin_x_name”中的所有对象。
这个功能是否需要一些插件?
答案 0 :(得分:1)
您可以构建一些处理插件/类型数组的函数来过滤所需的函数:
[{
"plugin": "plugin_a_name",
"types": ["js"]
}, {
"plugin": "plugin_b_name"
}]
在上面的子配置中,它只会复制plugin_a
的JS文件和plugin_b
的所有类型(JS / CSS)。
然后,您可以遍历所有已过滤的插件/类型,并从配置path.json
文件中获取它们(如果存在):
var gulp = require('gulp'),
config = require('./path.json');
function copyTask(target) {
//iterate over config files for the specified type
for (src in target) {
console.log("copy from " + src + " to " + target[src]);
gulp.src(src).pipe(gulp.dest(target[src]));
}
}
function copyFilter(pluginFilter) {
//loop on filter
for (var obj in pluginFilter) {
var pluginVal = pluginFilter[obj];
//check config has plugin
if (config[pluginVal.plugin]) {
if (pluginVal.types) {
//loop on type type filter
for (var type in pluginVal.types) {
var typeVal = pluginVal.types[type];
// check config has type
if (config[pluginVal.plugin][typeVal]) {
copyTask(config[pluginVal.plugin][typeVal]);
} else {
console.log("type " + typeVal + " not found for plugin " + pluginVal.plugin);
}
}
} else {
//iterate over all the types here
for (type in config[pluginVal.plugin]) {
copyTask(config[pluginVal.plugin][type]);
}
}
} else {
console.log("plugin " + pluginVal.plugin + " not found");
}
}
}
gulp.task('copyFromJson', function() {
copyFilter([{
"plugin": "plugin_a_name",
"types": ["js"]
}, {
"plugin": "plugin_b_name"
}]);
});
gulp.task('default', ['copyFromJson']);