azangru
azangru

Reputation: 2738

Gulp: preserving folder structure on destination for individual files

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?

Upvotes: 3

Views: 2824

Answers (1)

Vlad Bezden
Vlad Bezden

Reputation: 89547

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));
});

Upvotes: 7

Related Questions