Gulp: preserving folder structure on destination for individual files

北城余情 提交于 2019-12-07 11:57:05

问题


Let’s say we have the following folder structure:

rootDirectory
     │
     │
     ├──a
     │  ├──a.txt
     │
     ├──b
     │  ├──a
     │     ├──a.txt
     │
     ├──c.txt

also, let’s say we need to write a Gulp task that will take a.txt in the a folder, and c.txt; perform some manipulations on them, and then pipe them into the build directory. What I want is for the files copied in the build folder to keep their directory structure in the build folder (and I do not want files that were not supposed to be processed by the task to get in the build folder), like so:

rootDirectory
     │
     │
     ├──a
     │  ├──a.txt
     │
     ├──b
     │  ├──a
     │     ├──a.txt
     │
     ├──c.txt
     │
     ├──build
          │
          ├──a
          │  ├──a.txt
          │          
          ├──c.txt

Now, here is what puzzles me. If I specify paths to specific files:

gulp.task('foo', function(){
    var files = [
        path.join(__dirname, 'c.txt'),
        path.join(__dirname, 'a/a.txt')
    ];
    gulp.src(files)
        .pipe(gulp.dest(path.join(__dirname, build));
});

then I will flatten the folder structure in the build directory.

If, however, I use the globbing pattern:

gulp.task('foo', function(){
    var files = [
        path.join(__dirname, '**/c.txt'),
        path.join(__dirname, '**/a/a.txt')
    ];
    gulp.src(files)
        .pipe(gulp.dest(path.join(__dirname, build));
});

then the folder structure is preserved, but this globbing pattern will also target b/a.txt, which I do not want.

Is there a way to achieve what I describe in Gulp? Basically, telling Gulp: "Here, take this file, do whatever you need with this, and put it in another path keeping the folder structure starting from this root path"? Apart from specifically negating globbing paths that I do not want to match?


回答1:


In order to preserve hierarchy you should pass {base: "."} parameter to the gulp.src. Something like this:

gulp.task('foo', function(){
    var files = [
        path.join(__dirname, 'c.txt'),
        path.join(__dirname, 'a/a.txt')
    ];
    gulp.src(files, {base: '.'})
        .pipe(gulp.dest(path.join(__dirname, build));
});


来源:https://stackoverflow.com/questions/35220618/gulp-preserving-folder-structure-on-destination-for-individual-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!