Created
January 1, 2024 21:51
-
-
Save ZachWatkins/6204e05c4f8adbb331564342495e6d4c to your computer and use it in GitHub Desktop.
Vite plugin for including HTML files like Apache SSI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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