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

3
我正在尝试使用gulp-proceesshtml(https://github.com/julien/gulp-processhtml)来删除我构建版本中的一些不需要的代码,但问题是该任务需要提供一个文件名。 gulp.src('test.html').pipe(processhtml('test.html')); 但是当我处理文件夹中的所有HTML文件时,我无法弄清楚如何工作。 gulp.src('*.html).pipe(processhtml('filename here'));
2个回答

5

我知道这个问题已经很老了,但是为了得到一种更短的解决方案,你可以使用 gulp-tap,像这样:

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

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


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, ''));

我只是使用它,因为它允许我在构建“<!-- build:remove-->Dev code<!-- /build -->”时删除一些代码。如果有其他插件,我很乐意使用。 - woutr_be
在开发过程中添加代码可能更明智。这样做会减少错误(例如:您不会意外地将开发代码部署到服务器上)。代码是定制的还是只是livereload片段?如果不知道确切的内容,很难提出建议。 - OverZealous
根据我的当前开发堆栈,这是最好的方法,有一些东西我想在本地看到,但不想在实际构建中出现。而在本地执行的代码只是为了客户端进行小型重定向,以免他们遇到错误页面。因此,我唯一需要的就是能够从HTML文件中删除几行JavaScript的工具。 - woutr_be
1
使用 gulp-replace 怎么样:.pipe(replace(/<-- remove-this -->[\s\S]*<-- \/remove-this -->/g, '')) - OverZealous

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接