sagold / handlebars-webpack-plugin

Renders your html-template at build time
161 stars 45 forks source link

Addition of IMG tag processing #23

Closed yerzhant closed 6 years ago

yerzhant commented 6 years ago

Could you please add processing of img tags in templates, so that they appear in the dist and be watchable by webpack dev server.

Thanks in advance.

sagold commented 6 years ago

Hi yerzhant.

You can require images from your html if you use the loader-version of this plugin, found here: https://github.com/sueddeutsche/handlebars-render-loader. Within your loader chain, prepend the html loader to the handlebars-render-loader, which will ensure that images are put into your build.

Your configuration then might look something along theese lines:

{
    test: [
        path.join(__dirname, "app", "index.hbs")
    ],
    use: [
        {
            loader: "file-loader",
            options: {
                name: "[name].html"
            }
        },
        {
            loader: "extract-loader"
        },
        {
            loader: "html-loader",
            options: LOADER_CONFIG.html
        },
        {
            loader: "handlebars-render-loader",
            options: LOADER_CONFIG.handlebarsRender
        }
    ]
}
yerzhant commented 6 years ago

Hi Sascha,

Thank you for the reply. I've hooked to the onBeforeSave like this:

    onBeforeSave(h, html, t) {
        const images = htmlParser(html, (tag, attr) => {
            return tag === "img" && attr === "src";
        });
        images.forEach(img => {
            const src = __dirname + "/src/" + img.value.replace(/\.\.\//g, "");
            const tgt = module.exports.output.path + "/" + img.value.replace(/\.\.\//g, "");
            fs.mkdirpSync(path.dirname(tgt));
            fs.copyFileSync(src, tgt);
            handlebarsPlugin.registerGeneratedFile(tgt, fs.readFileSync(tgt));
        });
        return html;
    }

Appreciate you for your solution.