Search code examples
webpackparceljs

How to import HTML into HTML while build?


I have a project with the following structure:

my-site
├── home.html
├── about.html
└── shared
    ├── header.html
    └── footer.html

my-site\home.html:

<html>
    <!-- Insert contents of .\shared\header.html here -->
    <span>home</span>
    <!-- Insert contents of .\shared\footer.html here -->
</html>

my-site\about.html:

<html>
    <!-- Insert contents of .\shared\header.html here -->
    <span>about</span>
    <!-- Insert contents of .\shared\footer.html here -->
</html>

my-site\shared\header.html:

<div>header</div>

my-site\shared\footer.html:

<div>footer</div>

I need a build operation that creates a dist directory with the following structure:

dist
├── home.html
├── about.html
└── shared
    ├── header.html
    └── footer.html

dist\home.html:

<html>
<div>header</div>
    <span>home</span>
<div>footer</div>
</html>

dist\about.html:

<html>
<div>header</div>
    <span>about</span>
<div>footer</div>
</html>

The content of dist\shared\header.html and dist\shared\footer.html may be the same as their my-app counterparts.

My intent is similar to this Medium post, however, it uses client side JavaScript (document.onload) to fetch the shared HTML. I want to generate static HTML files that are fetched in a single GET.

Are there any known approaches to achieve this using any bundler?


Solution

  • Use handlebars-webpack-plugin to inject handlebars partials into your handlebars templates. Example usage can be found here.