handlebars-webpack-plugin icon indicating copy to clipboard operation
handlebars-webpack-plugin copied to clipboard

Process images in .hbs

Open brightpixels opened this issue 5 years ago • 3 comments

Hello, I need to compile hbs files to html at build time which is plugin is doing. However, it doesn't process the images. Anyway to ensure webpack processes the images founds in the handlebars files? Using the loader version of this plugin isn't an option as I need the hbs to be compiled at build time (this is a similar question to mine https://github.com/sagold/handlebars-webpack-plugin/issues/23).

brightpixels avatar Jul 19 '19 16:07 brightpixels

Hi brightpixels.

Sorry, im short in spare time right now. Just as a side note: the mentioned loader does compile the hbs-files on build time, too.

sagold avatar Aug 01 '19 19:08 sagold

Thanks. I didn't realise the other one works at build time as well!

brightpixels avatar Aug 03 '19 06:08 brightpixels

If anyone else is struggling with this, it's pretty straightforward with node-html-parser Ex:

      onBeforeSave: function (Handlebars, html, f) {
        const root = htmlParser.parse(html);
        let img = root.querySelectorAll("img");

        img.forEach((img) => {
          const str = img.rawAttrs;
          const regex = /src=['"](.*?)['"]/;
          const imgVal = regex.exec(str)[1];

          const src = paths.src + "/" + imgVal.replace(/\.\.\//g, "");
          const tgt = module.exports.output.path + "/" + imgVal.replace(/\.\.\//g, "");
          fs.copyFileSync(src, tgt);
        });
        return html;
      },

jakeols avatar Sep 23 '20 01:09 jakeols