Gulp - 复制和重命名文件

2022-01-12 00:00:00 javascript gulp gulp-watch

我对 Gulp 非常陌生.我基本上是在尝试查看修改过的 JavaScript 文件,然后用新名称制作它的新副本.(最终会有一些处理,但罗马不是一天建成的).

I'm extremely new to Gulp. I'm basically trying to watch for a modified JavaScript file, and then make a new copy of it with a new name. (eventually there'll be some processing on it, but Rome wasn't built in a day).

我的(天真的)尝试是这样的:

My (naive) attempt is this:

gulp.task('default', function() {

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

});

这会获取修改后的文件并成功地将其复制到现在名为 foobar.js 的文件夹中.有什么简单的方法可以替换 gulp.dest('foobar.js') ,只需复制并重命名 src 文件吗?

This takes the modified file and successfully copies it into a folder now called foobar.js. Is there anything simple I can replace gulp.dest('foobar.js') with that will simply copy and rename the src file in place?

编辑

就地复制,我的意思是我想获取修改后的文件,并在它当前所在的位置用一个新名称复制它.相当于单击文件(在 Windows 中)并按 control-c control-v,然后重命名生成的文件.

By copy in place, I mean I want to take the modified file, and make a copy of it right where it currently is with a new name. The equivalent of clicking the file (in windows) and hitting control-c control-v, then renaming the resulting file.

推荐答案

我不是 100% 确定你的意思

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. 查看父目录下的所有.js文件和
  2. 将它们复制到 cwd(当前工作目录)并
  3. 命名所有副本,无论源文件,相同的东西
  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

那么你可以使用 gulp-rename 来做到这一点:

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('.'));
  });
});

在这种情况下,输出文件名是 newFileName.js

In this case, the output filename is newFileName.js

为了使用该模块,您需要使用 npm 安装 gulp-rename 包(即:npm install gulp-rename).

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

更多示例可在 npm @ https://www 的包详细信息页面上找到.npmjs.com/package/gulp-rename#usage

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

相关文章