Gulp.js从.src()获取文件名

时间:2014-04-16 03:58:45

标签: javascript node.js gulp

我正在尝试使用gulp-proceesshtmlhttps://github.com/julien/gulp-processhtml)删除构建版本中的一些不需要的代码,问题是该任务需要提供文件名。

gulp.src('test.html').pipe(processhtml('test.html'));

但是当我处理文件夹中的所有HTML文件时,我无法弄清楚这是如何工作的

gulp.src('*.html).pipe(processhtml('filename here'));

2 个答案:

答案 0 :(得分:5)

就个人而言,听起来这是你想要完成的错误插件。 见下文

但是,由于它不清楚您使用它的是什么,因此您可以使用node-glob逐个处理每个文件:

var glob = require('glob')
    // you also need event-stream for merging the streams
    es = require('event-stream');

gulp.task('myTask', function() {
    var files = glob.sync('*.html'),
        streams;
    streams = files.map(function(file) {
                // add the *base* option if your files are stored in
                // multiple subdirectories
        return gulp.src(file, {base: 'relative/base/path'})
                // may need require('path').filename(file)
                .pipe(processhtml(file));
    });

    return es.merge.apply(es, streams);
});

这将从与初始模式匹配的每个文件中创建一个异步流。


只需从文件中删除一些文字,即可使用gulp-replace,如下所示:

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

gulp.src('*.html')
   // replaces all text between
   // <!-- remove-this --> and <!-- /remove-this -->
   .pipe(replace(/<!--\s*remove-this\s*-->[\s\S]*?<!--\s*\/remove-this\s*-->/g, ''));

答案 1 :(得分:4)

我知道这个问题很旧,但是对于更短的解决方案,您可以使用gulp-tap,如下所示:

.pipe(tap(function(file, t) {
    console.log(file.path);
 }))

如果您需要在管道的其他步骤中使用文件名,您可以将其存储在变量中并将其用于下一步。

相关问题