mike
mike

Reputation: 8141

Webpack plugin to attach static JSON object to output

I am trying to write a webpack plugin that will go into a directory containing html files, open each, remove new lines, and generate an object to attach as a static property to my output file (which is a var).

The object would look something like:

{
  htmlFile1: '<p>some html one!</p>',
  htmlFile2: '<span>some html two!</span>
}

Then I would like it to be attached to my output like:

App.templates = { .... }

The creation of the object is done. I'm just struggling with webpack and figuring out how to attach it to the main object. Should I just write it to disk and require it? Or is there a way to add it to the bundle via the plugin?

I'm using Rivets.js as a template engine and I have not been able to find anything out there that does something like this already.

Also worth noting, all I'm using is webpack and npm. No Grunt/Gulp/etc

Thanks so much! Mike

Upvotes: 0

Views: 584

Answers (1)

SimpleJ
SimpleJ

Reputation: 14768

You could use webpack's require.context to import all html files in a directory as text, process the text, and export the results as a single object:

const requireTemplate = require.context('./templates', false, /\.html$/);

module.exports = requireTemplate.keys().reduce((templateMap, templatePath) => {
  const templateName = templatePath.match(/\/(\w*?)\.html/)[1]; // get filename without path and extention
  templateMap[templateName] = require(templatePath);
  return templateMap;
}, {});

Upvotes: 0

Related Questions