sagold / handlebars-webpack-plugin

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

Compile Templates on data change #20

Closed kelvinlouis closed 6 years ago

kelvinlouis commented 7 years ago

Hi,

Is it possible to compile the templates when the data (JSON) has been changed?

kelvinlouis commented 7 years ago

Currently, I am working around this the following way:

const fs = require('fs');
const chalk = require('chalk');

...
...
new HandlebarsPlugin({
  ...
  partials: [
        path.join(process.cwd(), "views", "partials", "**", "*.hbs"),
        path.join(process.cwd(), "views", "data", "**", "*.json")
  ],
  ...
  /**
     * Circumvent caching of require() and always access from file system.
   */
      onBeforeRender: function (Handlebars, data) {
        try {
          return JSON.parse(fs.readFileSync(`${env.dataFile}`, 'utf8'));
        } catch (error) {
          console.log(chalk.red(`Error encountered when parsing ${env.dataFile}:`), error.message);
          return data;
        }
      },

Adding the data files to the partials ensures the templates get rerendered/compiled. I use fs.readFileSync to read an uncached version of the changed data file.

I might remove the entry from partials and try to accomplish it with just BrowserSync. But I couldn't find a way to recompile them yet.

sagold commented 6 years ago

Yes it is. The watch on the json-file is a wanted features. I gladly add it, but cannot tell when.

Regards. sagold

sagold commented 6 years ago

This was quick: 6865e7777e981202f3a92b3778b47bca17c3e3dd. Added and published with v1.3.0. Just add an absolute filepath instead of an object to the data-property.

Does it work?