Skip to content

Instantly share code, notes, and snippets.

@ZachWatkins
Created January 1, 2024 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZachWatkins/6204e05c4f8adbb331564342495e6d4c to your computer and use it in GitHub Desktop.
Save ZachWatkins/6204e05c4f8adbb331564342495e6d4c to your computer and use it in GitHub Desktop.
Vite plugin for including HTML files like Apache SSI
import fs from 'fs';
export default function includeHtml(mode) {
return {
name: 'insert-views',
/**
* Replace HTML include comments with the content of the included file.
* @param {string} html
* @returns {string}
* @example <!--#include file="header.html" -->
*/
transformIndexHtml(html) {
const pattern = /<!--#include\s+file="([^"]+)"\s*-->/g;
const matches = html.match(pattern);
if (!matches) {
return html;
}
let newHtml = html;
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const filePath = match.replace(pattern, '$1').replace('./', '').replace('../', '');
const fileContent = fs.readFileSync(`src/${filePath}`, 'utf-8');
newHtml = newHtml.replace(match, fileContent.toString());
}
return newHtml;
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment