Looking for way to copy files in gulp and rename based on parent directory

node.jsGulp

node.js Problem Overview


For each module I have some files that need to be copied over to the build directory, and am looking for a way to minimize the repeated code from this:

gulp.src('./client/src/modules/signup/index.js')
  .pipe(gulp.dest('./build/public/js/signup'));

gulp.src('./client/src/modules/admin/index.js')
  .pipe(gulp.dest('./build/public/js/admin'));

to something like this:

gulp.src('./client/src/modules/(.*)/index.js')
  .pipe(gulp.dest('./build/public/js/$1'));

Obviously the above doesn't work, so is there a way to do this, or an npm that already does this?

Thanks

node.js Solutions


Solution 1 - node.js

Not the answer, but applicable to this question's appearance in search results.

To copy files/folders in gulp

gulp.task('copy', () => gulp
  .src('index.js')
  .pipe(gulp.dest('dist'))
);

Solution 2 - node.js

The best way is to configure your base when sourcing files, like so:

gulp.src('./client/src/modules/**/index.js', {base: './client/src/modules'})
  .pipe(gulp.dest('./build/public/js/'));

This tells gulp to use the modules directory as the starting point for determining relative paths.

(Also, you can use /**/*.js if you want to include all JS files...)

Solution 3 - node.js

return gulp.src('./client/src/modules/(.*)/index.js')  
  .pipe(gulp.dest('./build/public/js/$1'));

Worked for me !

Solution 4 - node.js

Use for preserve input directory tree will be preserved.

.pipe(gulp.dest(function(file) {
    var src = path.resolve(SRC_FOLDER);
    var final_dist = file.base.replace(src, '');
    return DIST_FOLDER + final_dist;
}))

Using this, you can put in the src: .src(SRC_FOLDER + '/**/*.js').

The others answers not worked for me (like using base: on src()}, because some plugins flatten the directory tree.

Solution 5 - node.js

copy files in parallel

gulp.task('copy', gulp.parallel(
() =>  gulp.src('*.json').pipe(gulp.dest('build/')),
() =>  gulp.src('*.ico').pipe(gulp.dest('build/')),
() =>  gulp.src('img/**/*').pipe(gulp.dest('build/img/')),
)
);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchrisView Question on Stackoverflow
Solution 1 - node.jsKirk StrobeckView Answer on Stackoverflow
Solution 2 - node.jsOverZealousView Answer on Stackoverflow
Solution 3 - node.jsuser2977367View Answer on Stackoverflow
Solution 4 - node.jsbrnmonteiroView Answer on Stackoverflow
Solution 5 - node.jsDan AlboteanuView Answer on Stackoverflow