6

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 

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Now, how can I get the file name and not the full path? "file.name" did not work. Also, how could discover what all of the properties in the FILE object are?
@brOlite - file seems to be a vinyl object, see npmjs.com/package/vinyl. Using file.relative worked for me.
3

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; })); 

1 Comment

Not to say the accepted answer isn't a solution but I found gulp-insert to be much more flexible for my use case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.