@octamap/expose-scripts
v1.0.2
Published
Seamless import of module scripts in HTML
Readme
Expose Scripts
Use ES module scripts directly in your HTML with auto-awaiting!
This Vite plugin lets you import module scripts in HTML and seamlessly call their exports — even before they’ve loaded. It does this by injecting smart wrappers that defer execution until your script is ready.
✨ Features
- 💡 Call module exports directly in HTML using
await– no need to worry about load timing. - 🔍 Auto-detects which scripts and exports are used.
- 🧠 Injects a smart wrapper that defers execution until the export is available.
- 🚀 Works in dev and production, with automatic ID-based export referencing.
- 🧪 Optional debug mode.
🔧 Installation
npm install @octamap/expose-scripts --save-dev📦 Usage
vite.config.ts
import { ExposeScripts } from '@octamap/expose-scripts';
export default {
plugins: [
ExposeScripts() // optional
]
}💡 How It Works
This plugin allows you to write HTML like this:
index.html
<script expose type="module" src="./scripts/loadSpots.ts"></script>
<body>
<div x-init="await loadSpots(system, $data)"></div>
</body>And it transforms it into:
index.html (compiled)
<script>
const e3c = (key, ...args) => new Promise((resolve) => {
if (key in window) {
resolve(window[key](...args));
} else {
(window[`${key}_r`] ||= []).push((fn) => resolve(fn(...args)));
}
});
window.e58 = (key, fn) => {
window[key] = fn;
window[`${key}_r`]?.forEach((c) => c(fn));
delete window[`${key}_r`];
};
</script>
<body>
<div x-init="await e3c('loadSpots_547', system, $data)"></div>
</body>loadSpots.ts
export function loadSpots(system: string, data: any) {
// your code
}dist/loadSpots.js
export function loadSpots(system, data) {
// your code
}
window.loadSpots_547 = loadSpots;
window.loadSpots_547_r?.forEach((cb) => cb(loadSpots));🧠 Behind the Scenes
- Exports from
<script expose>modules are scanned and ID’d. - References in HTML like
loadSpots()are replaced withawait e3c('loadSpots_547'). - A loader script (
expose-script-xxxx.js) is injected to handle the async magic. - Works with both
.tsand.jsmodule scripts.
🛠 Options
| Option | Type | Default | Description |
| ----------- | --------- | ------- | -------------------------------------- |
| debugMode | boolean | false | Enables verbose logging for debugging. |
🧪 Tips
- Use
x-init="await myFunc(...args)"or similar Alpine/HTMX integrations. - Script references are updated even inside quoted strings.
- This is especially useful for component-based UIs where HTML is treated as a first-class citizen.
📜 License
MIT
