1

I've read Get the current file name in gulp.src(), and it seems like it's approaching what I am attempting to do, but I need help.

Consider the following function in a gulpfile.js:

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe($.if(PRODUCTION, inliner('dist/css/app.css')))
    .pipe(gulp.dest('dist'));
}

And inliner(), to be thorough (also in the gulpfile):

function inliner(css) {
  var css = fs.readFileSync(css).toString();
  var mqCss = siphon(css);

  var pipe = lazypipe()
    .pipe($.inlineCss, {
      applyStyleTags: false,
      removeStyleTags: false,
      removeLinkTags: false
    })
    .pipe($.replace, '<!-- <style> -->', `<style>${mqCss}</style>`);

  return pipe();
}

These functions take an external CSS file and inline them into the respective HTML for email.

I really want to know how to do something like this:

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe($.if(PRODUCTION, inliner('dist/css/' + file.name + '.css')))
    .pipe(gulp.dest('dist'));
}

And you might ask yourself, "why?" Well, I don't have just one CSS file. If everything from app.css was to be inlined, there would be a lot more styles applied than were actually necessary.

So I want to inline:

email1.css    ----  to  ------->    email1.html
email2.css    ----  to  ------->    email2.html
email3.css    ----  to  ------->    email3.html

And so on. Essentially, I want to get the name of the HTML file being processed at that moment in the Gulp Stream, save it as a variable, and then pass it into the inliner('dist/css/' + file.name + '.css') bit. I've exhausted every bit of Gulp Knowledge I have and have come up completely and utterly blank.

Community
  • 1
  • 1
ethfun
  • 13
  • 1
  • 4

1 Answers1

2

Basically what you need to do is send each .html file in your stream down its own little sub stream with its own inliner(). The gulp-foreach plugin let's you do just that.

Then it's just a matter of determining the simple name of your file from its absolute path. The node.js built-in path.parse() got you covered there.

Putting it all together:

var path = require('path');

function inline() {
  return gulp.src('dist/**/*.html')
    .pipe($.if(PRODUCTION, $.foreach(function(stream, file) {
       var name = path.parse(file.path).name;
       return stream.pipe(inliner('dist/css/' + name + '.css'));
     })))
    .pipe(gulp.dest('dist'));
}
Sven Schoenung
  • 30,224
  • 8
  • 65
  • 70