【问题标题】:Deleting files in a gulp task在 gulp 任务中删除文件
【发布时间】:2016-05-04 17:03:07
【问题描述】:

我有一个 gulp 任务,我想获取一些源文件并将它们复制到 build/premiumbuild/free,然后从中删除一些额外的文件 build/free.

我的尝试是这样做的:

gulp.task("build", ["clean"], function () {
  gulp.src(["src/*", "!src/composer.*", "LICENSE"])
    .pipe(gulp.dest("build/premium"))
    .pipe(del(["build/free/plugins/*", "!build/free/plugins/index.php"]))
    .pipe(gulp.dest("build/free"));
});

这会导致错误:

TypeError: dest.on is not a function
    at DestroyableTransform.Stream.pipe (stream.js:45:8)
    at Gulp.<anonymous> (/Users/gezim/projects/myproj/gulpfile.js:9:6)

如何在删除端口时完成此操作?有没有更好的方法来做到这一点?

【问题讨论】:

  • 我没有得到这里的操作顺序。目的似乎是删除尚未复制的文件(.pipe(del(..)))(.pipe(gulp.dest("build/free")))。有没有理由 del 应该在复制到 build/freepipe 之前?
  • @Louis 我在复制后删除了它,但这也不起作用。我想我想从管道中删除,事后看来这是没有意义的。

标签: javascript build gulp


【解决方案1】:

这是一个简单的clean 任务实现,带有gulp-del

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

gulp.task('clean', function(){
  return del(['folderA/js', 'folderA/css', 'folderB/js']);
});

在您的情况下,您可以在构建之后调用它(阅读“使用构建作为依赖项”):

gulp.task("build", function () {
  return gulp.src(['src/*', '!src/composer.*', 'LICENSE'])
    .pipe(gulp.dest("build/premium"))
    .pipe(gulp.dest("build/free"));
});

gulp.task("complete-build", ["build"] function(){
  return del(['build/free/plugins/*', '!build/free/plugins/index.php']);
});

然后调用“完成构建”任务来执行它。 老实说,这更像是一种类似“Grunt”的解决问题的方法,但使用 Gulp 完成了。也许建议在将内容写入build/free 文件夹之前对其进行过滤更符合 Gulp 精神。

2018 年 2 月更新

@gerl 报告的删除模块现已重命名为 del

var del = require('del');

gulp.task('clean', function(){
  return del(['folderA/js', 'folderA/css', 'folderB/js']);
});

【讨论】:

  • 我只想在将内容复制到 build/free 后删除内容。拥有clean 使其在build 运行之前运行。
  • 我已经更新了代码来做你想做的事。也许最好使用主动过滤器而不是写入和删除。
  • 现在是require('del')
【解决方案2】:

我会使用gulp-filter 仅删除不应从第二个目的地复制的内容。

我将任务的意图解释为希望src 中的所有内容都出现在build/premium 中。但是,build/free 应排除最初在 src/plugins 中但仍应包括 src/plugins/index.php 的所有内容。

这是一个有效的 gulpfile:

var gulp = require("gulp");
var filter = require("gulp-filter");
var del = require("del");

gulp.task("clean", function () {
  return del("build");
});

gulp.task("build", ["clean"], function () {
  return gulp.src(["src/**", "!src/composer.*", "LICENSE"])
    .pipe(gulp.dest("build/premium"))
    .pipe(filter(["**", "!plugins/**", "plugins/index.php"]))
    .pipe(gulp.dest("build/free"));
});

传递给filter 的模式是相对 路径。由于gulp.src 模式具有src/**,这意味着它们与src 相关。

还要注意,del 不能直接传递给 .pipe(),因为它返回一个承诺。它可以从任务中返回,就像 clean 任务一样。

【讨论】:

  • 非常感谢。这是正确的。
猜你喜欢
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多