Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulpjs concatenation and file names

I am looking for a way to insert the file name as a comment to each file in the stream. So after all you'll have a comment line with the file path, in the concatenated destination file.

What it does right now:

pseudocode: concat(file1, file2) 
# output: 
# contents of file 1
# contents of file 2

What I want to achieve:

pseudocode: concat(add_comments(file1, file2))
# output: 
# // file1
# contents of file 1
# // file2
# contents of file 2
like image 520
M K Avatar asked Apr 19 '14 11:04

M K


2 Answers

You can use the gulp-wrap plugin to prepend the file name before concatenating:

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

// in your task...
    return gulp.src('src/**/*.js')
        .pipe(wrap('//<%= file.path %>\n<%= contents %>'))
        .pipe(concat('output.js'))
        .pipe(gulp.dest('build'))

The wrap plugin allows you to wrap the contents of an item in the stream with a lodash (or underscore) template. It provides contents and file.* properties automatically.

The template I created is very simple: it outputs two slashes for the comment, the file's path, a newline, and then outputs the same contents as passed in.

like image 95
OverZealous Avatar answered Oct 04 '22 20:10

OverZealous


I did it with gulp-insert. It has a "transform" function where you are given the file contents, and the Vinyl file object, and you return the new contents. So you can do this:

.pipe(insert.transform(function(contents, file){
    return '// ' + file.path + '\n' + contents;
}));
like image 23
Nick Perkins Avatar answered Oct 04 '22 20:10

Nick Perkins