gulp-inject injects nothing

138 views Asked by At

Had to rewrite my gulpfile to gulp 4 but I'm facing problems of gulp-inject injecting nothing.

var gulp = require('gulp');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var rename = require('gulp-rename');
var cheerio = require('gulp-cheerio');
var inject = require('gulp-inject');
var path = require('path');

gulp.task('svgstore', function () {
  var svgs = gulp
    .src('static/svg/icons/src/*.svg')
    .pipe(svgmin(function (file) {
      var prefix = path.basename(file.relative, path.extname(file.relative));
      return {
        plugins: [{
          convertPathData: false
        }, {
          cleanupIDs: {
            prefix: prefix + '-',
            minify: true
          }
        }]
      }
    }))
    .pipe(cheerio(function ($, file) {
      $('[fill]').attr('fill', 'currentColor');
    }))
    .pipe(svgstore({ inlineSvg: true }))
    .pipe(gulp.dest('dest'));

  function fileContents(filePath, file) {
    return file.contents.toString();
  }

  return gulp
    .src('layouts/partials/src/inline-svg.html')
    .pipe(inject(svgs, { transform: fileContents }))
    .pipe(gulp.dest('layouts/partials'));
});

// Watch asset folder for changes
gulp.task("watch", function () {
  var watcher = gulp.watch("static/svg/icons/src/**/*")
  watcher.on('all', gulp.series('svgstore'))
})

// Set watch as default task
gulp.task("default", gulp.series("watch"))

I can't figure out why. I tried logging fileContents and it just says [Function: fileContents].

1

There are 1 answers

0
Eswar Abhi On

I faced the same issue. When I debugged the gulp-inject package, I figured out that the gulp-inject plugin look up for the startTag and the endTag in the source file/s (in your case, the source file/s is gulp.src('layouts/partials/src/inline-svg.html')) to inject the content, and when I printed out the tags to the console, the result is:

startTag: /<!\-\-\s*inject\b:svg\b\s*\-\->/gi
endTag: /<!\-\-\s*endinject\s*\-\->/gi

Conclusion: In the src file(i.e., inline-svg.html), insert the comments like below:

<div class="sr-only">
  <!-- inject:svg --><!-- endinject -->
</div>

Then, try to run the gulp task and it should work. Reference: https://github.com/w0rm/gulp-svgstore#inlining-svgstore-result-into-html-body

Gulp Version Used: ^5.0.4