0

I'm looking into migrating a large, homegrown build script for one of our projects to webpack.

One feature it has is it traverses a /views directory and copies the contents of the html files into a main index.html file. This allows us to easily use KnockoutJS's templating feature without putting everything in one file ourselves. Something like this:

for relative_path, full_path in walk(os.path.join(base, "views")):
    with open(full_path) as f:
        index.append("""<script type="text/html" id="{0}">""".format(relative_path))
        index.extend(f)
        index.append("</script>")

Ideally, I'd like to be able to do something like require('./views') and have it embed each .html file as <script type="text/html" id="views/foo">...</script>, injecting the text into the script tag and setting the id to the filepath. We have almost 100 different templates, so I'd like to avoid require()ing them individually.

Can I configure html-loader or html-webpack-plugin to do this? I'm wondering if I'll have to write my own webpack plugin or if there's a way I can configure an existing plugin to do what I want.

Thanks!

Seventh Helix
  • 727
  • 4
  • 9
  • 18

1 Answers1

1

I think you can accomplish this using require.context and the html loader.

function requireAll(requireContext) {
  return requireContext.keys().map(requireContext);
}
// requires and returns html files in the views directory
var modules = requireAll(require.context("./views", true, /^\.html$/));
modules.forEach(function(htmlTemplate){ 
   // code to add each template to document.body
}
cgatian
  • 22,047
  • 9
  • 56
  • 76