Danny de Vries
Danny de Vries

Reputation: 53

Include HTML partials with Webpack

I'm creating a Webpack Boilerplate to easily create A-Frame projects. I configured Webpack to bundle JS and include the A-Frame library. Since A-Frame heavily relies on declarative HTML I would like to include entities as HTML snippets so I don't get a huge index.html file.

So, I'm using HTML loader and trying to require / import other HTML files but they just show up as strings in the html.

Screenshot

Repository

How do I include HTML partials with html-loader? (or maybe another alternative)

Upvotes: 3

Views: 1457

Answers (1)

ngokevin
ngokevin

Reputation: 13233

I use Nunjucks and run a watcher/builder in my Webpack.

var Nunjucks = require('nunjucks');
var webpack = require('webpack');

// Set up templating.
var nunjucks = Nunjucks.configure(path.resolve(__dirname, 'src'), {noCache: true});

// Initial Nunjucks render.
var html = nunjucks.render('index.html', getContext());

fs.writeFileSync('index.html', html);

// For development, watch HTML for changes to compile Nunjucks.
// The production Express server will handle Nunjucks by itself.
if (process.env.NODE_ENV !== 'production') {
  fs.watch('src', {recursive: true}, (eventType, filename) => {        
    if (filename.indexOf('.html') === -1) {
      return;
    }
    console.log(`${filename} updated.`);
    try {
      fs.writeFileSync('index.html', nunjucks.render('index.html', getContext()));
    } catch (e) {
      console.error(e);
    }
  });
}

// ...

My tree:

index.html  // Compiled HTML.
src/
  index.html  // Template/Nunjucks HTML.
templates/
  somePartial.html

Then including:

{% include "./templates/somePartial.html" %}

Upvotes: 4

Related Questions