如何将当前源文件名添加到gulp-header

时间:2017-10-11 11:45:55

标签: gulp gulp-header

我缩小并整理供应商文件。将vendor.min.js中的脚本与一些信息(如原始文件名)分开会很好。我正在使用gulp-header为我的输出文件添加标题。

// Minify vendor JS
gulp.task('minify-vendor-js', function() {
    return gulp.src([
            'lib/**/*.js'
        ])
        .pipe(uglify())
        .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); })
        .pipe(header("// Vendor Package (compressed) - all rights reserved to the respective owners\r\n"))
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest('js'))
});

vendor.min.js应如下所示(注意"压缩来自......"标题:

// compressed from jquery.js
!function(e,t){"object"==typeof module&&"object"==typeof module.exports?mod ...

// compressed from bootstrap.js
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript ...

如何将当前gulp.src文件名放入标题文本?

1 个答案:

答案 0 :(得分:1)

您可以将gulp-tap添加到您的管道中,该管道可以检查流中的每个文件并从中提取信息:

var path = require('path');
var tap = require('gulp-tap');

// Minify vendor JS
gulp.task('minify-vendor-js', function() {
return gulp.src([
        'lib/**/*.js'
    ])
    .pipe(uglify())
    .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); })

    // .pipe(tap(function (file) {
    //    file.contents = Buffer.concat([
    //     new Buffer( '//  compressed from ' + path.basename(file.path) +  '\r\n'),
    //      file.contents
    //    ]);
    // }))

    // EDIT: replaced the above tap pipe with the following

    .pipe(header('//  compressed from ${filename} \r\n'))

    .pipe(concat('vendor.min.js'))

    // .pipe(tap(function (file) {
    //   file.contents = Buffer.concat([
    //     new Buffer( '// Vendor Package (compressed) - all rights reserved to the respective owners\r\n\r\n'),
    //     file.contents
    //   ]);
    // }))

   // either another tap (above) or header works here

    .pipe(header("// Vendor Package (compressed) - all rights reserved to the respective owners\r\n\r\n"))
    .pipe(gulp.dest('js'))
});

它看起来不像gulp-header允许你使用每个文件的函数作为参数,所以我建议使用gulp-tap。

编辑:gulp-header不允许使用函数参数,但可以提供对已解析文件和文件名ala ${filename}的访问权限。所以我删除了第一个tap管道以获得更简单的gulp-header管道。

相关问题