@octamap/bundle-raw
v1.0.3
Published
A plugin for bundling .raw imports
Readme
Bundle Raw
Bundle Raw is a Vite plugin that enhances HTML imports by automatically bundling and injecting JavaScript module dependencies found in <script type="module" src="..."> tags. This allows you to treat .html?raw imports as module-aware entry points in both development and production environments.
✨ Features
- 📦 Transforms raw HTML imports into dynamic module bundles.
- 🔍 Parses and rewrites HTML to inject generated JS chunks.
- 🧠 Handles virtual module resolution and chunk mapping internally.
- 🛠️ Works in both development (
vite dev) and production (vite build) modes. - 🧽 Cleans up original
<script>tags and replaces them with consolidated imports.
🚀 Install
npm install @octamap/bundle-raw --save-devNote: Replace the install command with the actual package name once published to npm.
🛠 Usage
In your vite.config.ts:
import { defineConfig } from 'vite';
import { BundleRaw } from '@octamap/bundle-raw';
export default defineConfig({
plugins: [BundleRaw()],
});Now when you import an HTML file with ?raw, the plugin will automatically:
- Parse the HTML and look for
<script type="module" src="...">tags. - Bundle those scripts into a virtual module.
- Replace the original script tags with a new
<script type="module">tag that points to the generated bundle.
📁 Example
// main.ts
import htmlContent from './index.html?raw';
document.body.innerHTML = htmlContent;<!-- index.html -->
<body>
<script type="module" src="./foo.js"></script>
<script type="module" src="./bar.js"></script>
</body>This gets transformed to something like:
<body>
<script type="module" src="/assets/index-bundle-raw.js"></script>
</body>Where /assets/index-bundle-raw.js contains:
import "./foo.js";
import "./bar.js";⚙ How It Works
During Transform:
- Converts HTML-in-JS back to HTML using
@octamap/html-js-convert. - Uses
@octamap/cheerio-bodyto locate module script tags. - Extracts and resolves relative paths.
- Generates a virtual JS chunk importing all those scripts.
- Rewrites the original HTML with a new
<script>referencing the chunk.
- Converts HTML-in-JS back to HTML using
During Build:
- Replaces placeholders with actual final asset paths after chunk hashing.
Virtual Modules:
- Handled internally and resolved using
resolveIdandload.
- Handled internally and resolved using
🔍 Dev vs Build
| Mode | Behavior |
| ---------- | ---------------------------------------------------------------------- |
| Dev | Uses timestamped /virtual: paths for hot reload and freshness. |
| Production | Outputs real chunks to /assets/ with stable naming and hashed paths. |
🧪 Caveats
- Only processes HTML imports that:
- End in
.html?raw - Contain
<script type="module" src="...">tags.
- End in
- Will not affect inline scripts or non-module scripts.
- Avoid using dynamic paths in script
srcattributes.
📦 Dependencies
📝 License
MIT – Happy bundling!
