javascriptnode.jsgulpgulp-inject

How can I insert the contents of a file in my index.html with gulp-inject?


Here's what I have tried so far:

gulp.task('watch-index-html', function () {
    gulp.watch(files, function (file) {
        return gulp.src('index/index.html')
            .pipe(inject(gulp.src(['index/base3.html']), {
                starttag: '<!-- inject:base3:html -->'
            }))
            .pipe(print(function (file) {
                return "Processing " + file;
             }))
            .pipe(gulp.dest('./'));
    });
});

Here's what happened:

Before:

<body>
    abcd
    <!-- inject:base3:html -->
    <!-- endinject -->
    efgh

After:

<body>
    abcd
<!-- inject:base3:html -->
<link rel="import" href="/index/base3.html">
<!-- endinject -->
    efgh

What I expected to see was the actual contents of the file, not the line:

<link rel="import" href="/index/base3.html">

Can anyone tell me if I can do this "inserting contents of a file" with gulp-inject or if there's something else I should use. Note in the past I tried using gulp-mustache but I had problems where it seemed to insert the character (65279). I assume this was something related to the following question, but I was never able to get mustache to work for me:

How to avoid echoing character 65279 in php? (This question also relates to Javascript xmlhttp.responseText (ajax))

I hope someone can give me some advice either with gulp-inject or with gulp-mustache or any other way to insert the contents of a file in another file.


Solution

  • Use a custom transform function to inject the contents of the file:

    gulp.task('watch-index-html', function () {
      gulp.watch(files, function (file) {
        return gulp.src('index/index.html')
          .pipe(inject(gulp.src(['index/base3.html']), {
             starttag: '<!-- inject:base3:html -->',
             transform: function(filepath, file) {
               return file.contents.toString();
             }
          }))
          .pipe(print(function (file) {
            return "Processing " + file;
          }))
         .pipe(gulp.dest('./'));
      });
    });