Gulp - copy and rename a file

余生颓废 提交于 2019-11-30 16:46:33

I'm not 100% certain what you mean by

copy and rename ... in place

But, based on your current code, if you simply wish to:

  1. Watch all .js files in the parent directory and
  2. Copy them to the cwd (current working directory) and
  3. Name all copies, regardless of source file, the same thing

Then you could use gulp-rename to do just that:

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

gulp.task('default', function() {
  return gulp.watch('../**/**.js', function(obj) {
    gulp.src(obj.path)
      .pipe(rename('newFileName.js'))
      .pipe(gulp.dest('.'));
  });
});

In this case, the output filename is newFileName.js

In order to use the module, you'll need to install the gulp-rename package with npm (ie: npm install gulp-rename).

More examples are available on the package details page on npm @ https://www.npmjs.com/package/gulp-rename#usage

It wasn't pretty getting there, but in the end it appears this is what I want (with some ES6 transpiling in the middle).

The key appears to be the options object with a base property in the call to src. That seems to be what's needed to maintain the path of the current file in the call to dest.

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

gulp.task('default', function() {
    return gulp.watch('../**/$**.js', function(obj){
        if (obj.type === 'changed') {
            gulp.src(obj.path, { base: './' })
                .pipe(babel())
                .pipe(rename(function (path) {
                    path.basename = path.basename.replace('$', '');
                }))
                .pipe(gulp.dest(''));
        }
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!