2

I am moving a project that used grunt across to webpack.

I am using HTML snippets a lot to reuse HTML components across various files.

For HTML includes that do not require passing of variables I am using webpack html-loader.

For those that do I am using mustache and html-loader together.

This is working well at the top level, but is not recursive, so a snippet that contains another snippet just shows the include code, and not the interpolated HTML.

The easiest way to demonstrate was to create a simple repo that demonstrates the problem: https://github.com/JamieMcDonnell/webpack-html-loader

My HTML template is:

<html>
  <head>
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.16.6"></script>
  </head>
  <body>
      <%= require('html-loader?interpolate!./snippets/no-variables.html') %>
      <%= require('mustache-loader!html-loader?interpolate!./snippets/variable.html')({someVariable: 'MY VARIABLE'}) %>
      <%= require('html-loader?interpolate!./snippets/recursive.html') %>
  </body>
</html>

The first 2 includes are imported without a problem.

The 3rd, recursive.html, looks like:

<h1>I am a top level include</h1>
<%= require('html-loader?interpolate!./sub/sub.html') %>
<%= require('mustache-loader!html-loader?interpolate!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'}) %>

sub/sub.html and sub/variable.html are super simple, and should work. I suppose I am missing a property or something to enable recursive loading or something, but am unable to find it.

Please check the /dist/ folder for the result. Can anyone see what I am doing wrong here?

Thanks so much for your time and help ;)

user2115620
  • 101
  • 1
  • 10

1 Answers1

1

You need to import nested files like

${require('html-loader?!./sub/sub.html')}
${require('mustache-loader!html-loader?!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'})}
Jakub
  • 104
  • 1
  • 4
  • Thanks Jakub, though you were missing the interpolate command the ${} syntax helped me solve the issue. The correct includes are: ${require('html-loader?interpolate!./sub/sub.html')} ${require('mustache-loader!html-loader?interpolate!./sub/variable.html')({someVariable: 'MY SUB VARIABLE'})} Thanks a lot for your help! – user2115620 Feb 18 '20 at 09:42
  • @user2115620 you don't need to use the `interpolate` option in this snippet. If you're going to use `interpolate` through the whole app I would recommend to set `interpolate: true` in `webpack.config` then – Jakub Feb 18 '20 at 09:58