在Gulp中从第二个来源覆盖文件

我有一个像这样的目录结构;

foo/ - main.css - widgets.css - theme.css bar/ - theme.css - tinymce.css 

我想在Gulp中实现的是创build一个包含foo/中的所有文件的stream(如"foo/**/*.css" ),然后将它们与bar/的内容合并,以便任何文件在另一个中不存在,而另一个中存在的文件被覆盖。

最后,我应该有一个包含的stream;

 foo/main.css foo/widgets.css bar/theme.css bar/tinymce.css 

添加了bar/theme.css ,并将bar/theme.cssreplace为foo/theme.css 。 这应该也适用于foobar内的所有子文件夹。

我如何做到这一点? 我看了一些Gulp的合并包,但是他们似乎只是添加了这些文件,并且从来不replace它们。

有多种方法可以做到这一点。 以下的gulp文件将把目录ab所有内容合并为a final

  1. 如果文件存在,这个文件就会出现在final

  2. 如果文件存在于a不是 b ,则该文件将在final出现。

实际上, b的文件“覆盖” ab中的文件可以包含除b中的文件以外的文件。

解决scheme的核心是使用event-streammap方法来处理每个乙烯文件在stream过stream时,然后决定如何处理它。 请注意,下面的代码将创build一个乙烯基文件的所有问题视为“不存在”。 如果您想要从真正缺less的文件中区分权限错误,您可能需要详细检查错误。

 import gulp from "gulp"; import es from "event-stream"; import debug from "gulp-debug"; import vinylFile from "vinyl-file"; import fs from "fs"; import path from "path"; gulp.task("default", (callback) => { const a_path = "a/"; const b_path = "b/"; // We add the forward slash so that the comparison later works. const b_absolute = path.resolve(b_path) + "/"; return gulp.src([path.join(a_path, "**"), path.join(b_path, "**")], { nodir: true }) .pipe(debug({title: "before"})) .pipe(es.map((file, callback) => { // We want all the files in b. if (file.base === b_absolute) { callback(null, file); return; } // For files in a, we want only those that do not also // exist in b. vinylFile.read( path.join(b_path, file.relative), {base: b_path}, (err, override) => { // It does not exist in b, so we want it. All // errors are interpreted as "does not exist". if (err) { callback(null, file); return; } // It exists in b, so we don't want it. callback(); }); })) .pipe(debug({title: "after"})) .pipe(gulp.dest("final")); }); 

(如果需要说明:上面的代码符合ES6,如果你的文件gulpfile.babel.js并且安装了babel或者babel-core ,你可以运行这个文件。)

如果我有以下设置:

 $ find a -type f | xargs -n1 -t cat cat a/three from a cat a/two from a cat a/one from a cat a/four from a $ find b -type f | xargs -n1 -t cat cat b/two from b cat b/five from b cat b/four from b 

我运行上面的gulp文件,得到:

 $ gulp [11:36:10] Failed to load external module babel-core/register [11:36:10] Requiring external module babel/register [11:36:10] Using gulpfile /tmp/t12/test2.babel.js [11:36:10] Starting 'default'... [11:36:10] before a/four [11:36:10] before a/one [11:36:10] after a/one [11:36:10] before a/three [11:36:10] after a/three [11:36:10] before a/two [11:36:10] before b/five [11:36:10] after b/five [11:36:10] before b/four [11:36:10] after b/four [11:36:10] before b/two [11:36:10] after b/two [11:36:10] before 7 items [11:36:10] after 5 items [11:36:10] Finished 'default' after 37 ms 

如果我检查final

 $ find final -type f | xargs -n1 -t cat cat final/three from a cat final/two from b cat final/one from a cat final/five from b cat final/four from b