Gulp 复制并拼合文件和文件夹

Gulp copy and flatten files & folders

在我的应用程序中,我有以下 file/folder 结构:

/components
    /assets
    /navbar
        /assets
            /stylehseets
            /scripts
    /sidebar
        /assets
            /stylesheets
            /scripts
    /editor
        /assets
            /stylehseets
            /scripts
            /icons

然后我有一个 gulp 任务来将这些组件扁平化为一组工件。

var tools = {
    copy: function (src, dest) {
        return gulp
            .src(src)
            .pipe(gulp.dest(dest));
    }
};

gulp.task("create-artifacts", function () {
    tools.copy("./components/navbar/assets/**/*", "./artifacts");
    tools.copy("./components/sidebar/assets/**/*", "./artifacts");
    tools.copy("./components/editor/assets/**/*", "./artifacts");
});

这导致以下 file/folder 结构:

/artifacts
    /stylehseets
    /scripts
    /icons

问题是我的组件文件夹将包含越来越多的组件,所以我希望我的 gulp 任务更聪明一些。

比如说,我现在要添加

/components
    /messagebox
        /assets
            /stylehseets
    /listbox
        /assets
            /stylesheets
            /scripts

现在我需要进入 gulp 任务并为 messageboxlistbox 添加复制位置。

gulp.task("create-artifacts", function () {
    tools.copy("./components/navbar/assets/**/*", "./artifacts");
    tools.copy("./components/sidebar/assets/**/*", "./artifacts");
    tools.copy("./components/editor/assets/**/*", "./artifacts");

    // having to add these new components in...
    tools.copy("./components/messagebox/assets/**/*", "./artifacts");
    tools.copy("./components/listbox/assets/**/*", "./artifacts");
});

我真正想要的是这样的东西...

gulp.task("create-artifacts", function () {
    return tools.copy("./components/*/assets/**/*", "./artifacts");
});

但这并没有达到扁平化层次结构的预期效果。我该怎么办?

解决方案是使用 gulp-flatten

var flatten = require("gulp-flatten");

gulp.task("create-artifacts", function () {
    return gulp
        .src("./components/*/assets/**/*")
        .pipe(flatten({ includeParents: -1 }))
        .pipe(gulp.dest("./artifacts"));
});