使用gulp压扁父目录,但不能使用子目录

我组织了我的代码,以便在文件夹名称(如_DIRECTIVE上包含一些关键字。 我的意图是用gulp.src("**/*_DIRECTIVE/**/*")来编写一个能识别文件夹命名模式的gulp.src("**/*_DIRECTIVE/**/*")任务。 我想复制包含_DIRECTVE关键字的所有文件夹(及其子文件夹),并将它们放在单独的文件夹中。

我有一个文件夹结构,看起来像

 src |-folder-name_1_DIRECTVE/ | |-subfolder/ | | |-subsubfolder/ | | |-file.js | | | |-file.js | |-folder/ | |-folder-name_2_DIRECTVE/ | |-subfolder/ | | |-subsubfolder/ | | |-file.js | | | |-file.js | | |-folder/ |-subfolderfolder/ |-folder-name_3_DIRECTVE/ |-subfolder/ | |-subsubfolder/ | |-file.js | |-file.js 

使用gulp我想要输出

 output |-folder-name_1_DIRECTVE/ | |-subfolder/ | | |-subsubfolder/ | | |-file.js | | | |-file.js | |-folder-name_2_DIRECTVE/ | |-subfolder/ | | |-subsubfolder/ | | |-file.js | | | |-file.js | |-folder-name_3_DIRECTVE/ |-subfolder/ | |-subsubfolder/ | |-file.js | |-file.js 

我尝试使用gulp-flatten但它没有帮助,因为它也展平了我的_DIRECTIVE文件夹下的子文件夹。

请帮忙

       

网上收集的解决方案 "使用gulp压扁父目录,但不能使用子目录"

您可以使用gulp-rename与函数callback来删除相应的父文件夹:

 gulp.task('copy', function() { return gulp.src(['src/**/*_DIRECTIVE/**/*.js']) .pipe(rename(function(path) { path.dirname = path.dirname.replace(/^(.+[\\\/])?(?=[^\\\/]+_DIRECTIVE)/, ''); })) .pipe(gulp.dest('output')); }); 

假设与您的问题类似的文件夹结构,文件名称更改为清晰:

 $ find src -type f src/top-level_DIRECTIVE/directive1.js src/top-level_DIRECTIVE/subfolder1/subsubfolder1/directive1-sub.js src/folder-2/nested-2_DIRECTIVE/directive2.js src/folder-2/nested-2_DIRECTIVE/subfolder2/subsubfolder2/directive2-sub.js src/folder-3/double-nested/nested-3_DIRECTIVE/directive3.js src/folder-3/double-nested/nested-3_DIRECTIVE/subfolder3/subsubfolder3/directive3-sub.js $ gulp copy $ find output -type f output/top-level_DIRECTIVE/directive1.js output/top-level_DIRECTIVE/subfolder1/subsubfolder1/directive1-sub.js output/nested-2_DIRECTIVE/directive2.js output/nested-2_DIRECTIVE/subfolder2/subsubfolder2/directive2-sub.js output/nested-3_DIRECTIVE/directive3.js output/nested-3_DIRECTIVE/subfolder3/subsubfolder3/directive3-sub.js 

说明:

path.dirname将被传递给你的源模式的“基础”的文件名:

  • gulp.src('src/**/*.js')

    src/a.js path.dirname == "a.js"
    src/nested/folder/b.js path.dirname == "nested/folder/b.js"

  • 对于gulp.src('src/directives/**')

    src/directives/tab-directive/tabs.js path.dirname == "tab-directive/tabs.js"

当您更改重命名callback中传递的对象时,文件path被追加到输出path:

 .pipe(gulp.rename(function (path) { path.basename = 'flat-' + path.basename; }); // renames to: output/some-directory/flat-file1.js output/other-directory/flat-file2.js 

要从path中删除*_DIRECTIVE目录的父目录,请使用正则expression式:

 path.dirname = path.dirname.replace(/(.+[\\\/])?(?=[^\\\/]+_DIRECTIVE)/, ''); 
 /^(.+[\\\/])?(?=[^\\\/]+_DIRECTIVE)/ ^ at the start of the string ( )? match an optional group .+ with 1 or more characters [\\\/] and ending with a directory separator (\ or /) (?= ) followed by a group which is excluded from the match [^\\\/]+ which has a folder-name (no \, /) _DIRECTIVE followed by a literal _DIRECTIVE