1

I am trying to create a Browsersync middleware to replace a string in HTML files before they are served to the browser.

I'm not entirely sure this is even possible.

So far I am able to identify when a HTML file is being requested by:

function hublMiddleware (req, res, next) {
  var parsed = require("url").parse(req.url);

  if (parsed.pathname.match(/\.html$/)) {}

  next();
};

I can put a console.log() inside the if statement so I know it's working.

But from here I am genuinely stuck. I have searched for examples of how this may be done, e.g.

  res.removeHeader('Content-Length');

  res.pipe($.replace(/({{\s|\s}})|({%.*%})/g, '<!---->'))
    .pipe(res);

  return next();

But to no avail.

I should say I am using Browsersync with Gulp. Any help with this would be much appreciated!

Jonathon Oates
  • 2,912
  • 3
  • 37
  • 60

1 Answers1

1

This one does exactly what you want: bs-rewrite-rules

Here's how I used it:

gulp.task('serve', function () {
    browserSync({
        port: 8000,
        server: {
            baseDir: './'
        },
        plugins: ['bs-rewrite-rules'],
        rewriteRules: [
            {
                match: 'YOUR_GOOGLE_MAPS_API_KEY',
                replace:'<MY_ACTUAL_API_KEY>'
            }
        ]
    });

    gulp.watch(['*.html', 'css/**/*.css', 'js/**/*.js'], reload);
});
javaday
  • 11
  • 1