'How to include HTML partials using Vite?
Is it possible to include snippets of shared HTML using Vite (vanilla)? I'm looking for a way to have the HTML prerendered without injecting via JS.
Something like:
<html>
  <head>
    { include 'meta-tags' }
  </head>
  <body> 
    { include 'nav' }
    <h1>Hello World</h1>
  <body>
</html>
Solution 1:[1]
vite-plugin-handlebars was the solution I was looking for. Partials were super easy to set up with this package:
Setup:
// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';
export default {
  plugins: [
    handlebars({
      partialDirectory: resolve(__dirname, 'partials'),
    }),
  ],
};
File where you want to include partial:
<!-- index.html -->
{{> header }}
<h1>The Main Page</h1>
Rendered output:
<header><a href="/">My Website</a></header>
<h1>The Main Page</h1>
Solution 2:[2]
You could use the vite-plugin-html that enables EJS templates in index.html:
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
  plugins: [
    createHtmlPlugin({
      entry: 'main.js',
      /**
       * Data that needs to be injected into the index.html ejs template
       */
      inject: {
        data: {
          metaTags: `<meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
          nav: `<nav>
            <a href="https://google.com">Google</a> | 
            <a href="https://apple.com">Apple</a>
          </nav>`,
        },
      },
    }),
  ],
})
<!-- index.html -->
<html>
  <head>
    <%- metaTags %>
  </head>
  <body>
    <%- nav %>
    <h1>Hello World</h1>
  <body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | docta_faustus | 
| Solution 2 | tony19 | 
