A Vite plugin that enables importing HTML files as modules, supporting the HTML Modules proposal. Transform HTML files into JavaScript modules that export DOM nodes for use in your applications.
npm install @arcmantle/vite-plugin-html-module
# or
pnpm add @arcmantle/vite-plugin-html-module
# or
yarn add @arcmantle/vite-plugin-html-module
Add the plugin to your vite.config.ts
:
import { htmlModules } from '@arcmantle/vite-plugin-html-module';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
htmlModules()
]
});
Include the client types in your tsconfig.json
:
{
"compilerOptions": {
"types": ["@arcmantle/vite-plugin-html-module/client"]
}
}
Import HTML files using the with { type: 'html' }
syntax:
import template from './template.html' with { type: 'html' };
// The default export is a Document object
console.log(template); // Document
// Use the document as needed
document.body.appendChild(template.body.firstElementChild);
Enable element ID exports in your configuration:
import { htmlModules } from '@arcmantle/vite-plugin-html-module';
export default defineConfig({
plugins: [
htmlModules({ exportIds: true })
]
});
Given an HTML file like this:
<!-- template.html -->
<div id="container">
<h1 id="title">Hello World</h1>
<button id="my-button">Click me</button>
</div>
You can import both the document and individual elements:
import template, { container, title } from './template.html' with { type: 'html' };
// Access the full document
console.log(template); // Document
// Access individual elements by their IDs
console.log(container); // <div id="container">...</div>
console.log(title); // <h1 id="title">Hello World</h1>
// Elements with invalid JavaScript identifiers are exported with quotes
import template, { 'my-button': myButton } from './template.html' with { type: 'html' };
console.log(myButton); // <button id="my-button">Click me</button>
exportIds
boolean
false
id
attributes are exported as named exports. Elements with valid JavaScript identifiers are exported directly, while others are exported with quoted names.htmlModules({
exportIds: true // Enable ID-based exports
})
.html
files that use the with { type: 'html' }
import assertionDOMParser
instanceDocument
This plugin transforms HTML modules at build time, so the generated code runs in any environment that supports:
DOMParser
API (all modern browsers)Apache-2.0
This package is part of the Arcmantle Weave monorepo. Contributions are welcome!
Note: This plugin implements support for the HTML Modules proposal, which is still evolving. The syntax and behavior may change as the specification develops.