Looking for way to copy files in gulp and rename b

2019-01-10 03:37发布

问题:

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

回答1:

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...)



回答2:

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


回答3:

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

Worked for me !



回答4:

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.



回答5:

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/')),
)
);


标签: node.js gulp