Can Gulp overwrite all src files?

柔情痞子 提交于 2019-12-02 17:40:33
OverZealous

I can think of two solutions:

  1. Add an option for base to your gulp.src like so:

    gulp.src([...files...], {base: './'}).pipe(...)...
    

    This will tell gulp to preserve the entire relative path. Then pass './' into gulp.dest() to overwrite the original files. (Note: this is untested, you should make sure you have a backup in case it doesn't work.)

  2. Use functions. Gulp's just JavaScript, so you can do this:

    [...files...].forEach(function(file) {
        var path = require('path');
        gulp.src(file).pipe(rename(...)).pipe(gulp.dest(path.dirname(file)));
    }
    

    If you need to run these asynchronously, the first will be much easier, as you'll need to use something like event-stream.merge and map the streams into an array. It would look like

    var es = require('event-stream');
    
    ...
    
    var streams = [...files...].map(function(file) {
            // the same function from above, with a return
            return gulp.src(file) ...
        };
    return es.merge.apply(es, streams);
    

Tell gulp to write to the base directory of the file in question, just like so:

    .pipe(
        gulp.dest(function(data){

            console.log("Writing to directory: " + data.base);
            return data.base;
        })
    )

(The data argument is a vinyl file object)

The advantage of this approach is that if your have files from multiple sources each nested at different levels of the file structure, this approach allows you to overwrite each file correctly. (As apposed to set one base directory in the upstream of your pipe chain)

if you are using gulp-rename, here's another workaround:

var rename = require('gulp-rename');

...

function copyFile(source, target){
  gulp.src(source)
  .pipe(rename(target))
  .pipe(gulp.dest("./"));
}

copyFile("src/js/app.js","dist/js/app.js");

and if you want source and target to be absolute paths,

var rename = require('gulp-rename');

...

function copyFile(source, target){
  gulp.src(source.replace(__dirname,"."))
  .pipe(rename(target.replace(__dirname,".")))
  .pipe(gulp.dest("./"));
}

copyFile("/Users/me/Documents/Sites/app/src/js/app.js","/Users/me/Documents/Sites/app/dist/js/app.js");

I am not sure why people complicate it but by just starting your Destination path with "./" does the job.

Say path is 'dist/css' Then you would use it like this .pipe(gulp.dest("./dist/css"));

That's it, I use this approach on everyone of my projects.

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