pawajs-vite-plugin
v0.0.15
Published
pawajs vite plugin hot module replacement and safe components naming minification
Readme
pawajs-vite-plugin
A comprehensive Vite plugin suite for PawaJS that provides Hot Module Replacement (HMR) and intelligent code transformations.
✨ Features
pawajsPlugin()
- ✅ Minifier-safe returns for PawaJS component hooks
- 🔄 Automatic component name injection for
RegisterComponent() - ⚡ Works with both JavaScript and TypeScript
- 🧠 Uses
estree-walkerandmagic-stringfor efficient AST transforms
pawaHMR()
- 🔥 Hot Module Replacement for Pawa components and utilities
- 🎯 Intelligent file detection for components and global utilities
- ⚡ Fast HMR with custom event system
- 📦 Virtual module support for HMR client injection
- 💾 Best-effort state preservation across edits, with source-change detection (see State Preservation & Trade-offs)
📦 Installation
npm install pawajs-vite-plugin --save-dev⚠️ Requirements
__pawaDev.tool must be enabled
Live-instance HMR tracking in pawajs core is gated behind __pawaDev.tool. Component instances are only registered into the internal HmrComponentMap — the registry this plugin's client (src/reload.js) relies on to find and patch live DOM instances — when __pawaDev.tool is truthy at runtime.
If __pawaDev.tool is not set (misconfigured dev entry point, a build that imports pawajs in a way that skips dev-tool initialization, etc.), pawaHMR() will still send pawa-update events and the client will still receive them — but there will be no live instances to look up, and edits will silently fail to hot-patch anything, with no runtime error. If HMR appears to do nothing after a save, verify __pawaDev.tool is active before assuming the plugin or component is broken.
🚀 Usage
Basic Setup
import { defineConfig } from 'vite'
import { pawajsPlugin, pawaHMR } from 'pawajs-vite-plugin'
export default defineConfig({
plugins: [
pawaHMR(),
pawajsPlugin()
]
})pawajsPlugin() Configuration
Automatically transforms your PawaJS components:
// Input
RegisterComponent(MyButton)
// Output
RegisterComponent('MyButton', MyButton)Ensures minifier-safe return statements:
// Input
export default function MyComponent() {
runEffect()
return html`<div>Content</div>`
}
// Output
export default function MyComponent() {
runEffect()
const _pawaTemplate = html`<div>Content</div>`
return _pawaTemplate
}pawaHMR() Configuration
Enables HMR with optional configuration:
import { defineConfig } from 'vite'
import { pawaHMR } from 'pawajs-vite-plugin'
export default defineConfig({
plugins: [
pawaHMR()
]
})How It Works
The HMR plugin works in two parts:
Server-side (hmr):
- Detects PawaJS components - Files using PawaJS imports and APIs
- Tracks global utilities - Exported modules in
utils/,helpers/, orlib/folders - Invalidates modules - Properly clears the module cache for utilities
- Sends custom events - Notifies the client with detailed change metadata via
pawa-updateevent
Client-side (src/reload.js - auto-injected):
- Listens for updates - Receives
pawa-updateevents from the dev server - Re-imports modules - Dynamically re-imports updated component files with cache-busting timestamps
- Detects components - Checks which components are defined in the updated module by reference or name
- Updates component registry - Updates the PawaJS component map with new function implementations
- Re-renders instances - Automatically re-renders all active component instances in the DOM with the new code, attempting to preserve their state (see below)
- Handles utilities - For utility changes, re-imports dependent modules and re-renders affected components
Process flow:
File changes → Server detects → Sends pawa-update event → Client re-imports
↓
Direct component change → Directly update & re-render
↓
Utility change → Find importers → Re-import dependents → Update & re-render
↓
Graceful fallback → Full page reload if neededEvent Handling
The HMR client is automatically injected into your page via a virtual module. No additional setup is required on the client side — it handles component updates automatically.
If you need custom handling in your application:
if (import.meta.hot) {
import.meta.hot.on('pawa-update', async (data) => {
console.log('Pawa components updated:', data.files)
console.log('Kind:', data.kind) // 'component' or 'util'
// Custom logic can be added here if needed
// The automatic HMR client handles re-rendering
})
}💾 State Preservation & Trade-offs
When a component is hot-patched, pawajs core attempts to carry the previous run's state values into the new run rather than resetting everything on every save. This section documents how that works and where it intentionally falls short, so failures are predictable rather than mysterious.
Identity is by useInsert key name, not call order
PawaJS has no "rules of hooks" — $state() can be called conditionally, in any order, any number of times. Because of that, state identity across a hot reload is not determined by call position (the way React Fast Refresh does it). Instead, identity comes from the string keys a component explicitly exposes via useInsert({...}):
useInsert({ count, name })Only state exposed this way participates in HMR state preservation. State that's created via $state() but never passed through useInsert has no identity across reloads and will always reset to its initial value on every hot edit — this is a known, accepted gap, not a bug to be chased down, since state that never reaches the template generally has no user-visible continuity to preserve anyway.
Initializer-change detection
A naive "always restore the old value for a matching key" approach has a real failure mode: if you edit $state(0) to $state(5) in source and save, a naive restore would silently overwrite your new 5 with the old runtime value, making the edit appear to do nothing.
To avoid this, each useInsert-exposed state's initial value is snapshotted on every reload and compared against the previous snapshot:
- Snapshot unchanged → treated as a normal edit elsewhere in the file; the old runtime value (post-interaction, not the initial) is restored as usual.
- Snapshot changed → treated as an intentional edit to that state's initializer; the freshly computed value is left standing instead of being overwritten.
Comparison is done via JSON.stringify on cloned, de-reactivated values — proxies and live bindings are stripped out before comparing, since comparing live references would always report "unchanged" (an object compared to itself).
Known trade-offs (accepted)
These are deliberate, understood limitations rather than defects:
- Functions inside objects/arrays are detected and treated as "unknown."
JSON.stringifysilently drops function-valued properties. AnyuseInsertvalue containing a function anywhere in its structure (e.g.{ increment: [{ increase: () => count.value++ }] }) is marked as un-comparable, and that key always falls back to old (always-restore) behavior rather than risking a false "unchanged" verdict. undefined-valued object properties (not array entries) can still slip past detection.JSON.stringifyomitsundefined-valued object keys entirely before any replacer function is invoked for them, so this specific case can't be caught by the replacer-based detection used here.undefinedvalues inside arrays (whichJSON.stringifycoerces tonullrather than omitting) are caught. In practice this only matters if state is deliberately initialized toundefinedinside an object literal rather than a concrete default likenullor0— considered narrow enough to accept rather than build further defenses for.- Nominal identity, not semantic identity. Because matching is by
useInsertkey name, if a key is removed and a different, unrelated state happens to be reintroduced under the same name in the same edit, the old value will be restored into the new, unrelated meaning. This is the same class of ambiguity as React's listkeyprop — the developer's naming is treated as the source of truth, and this can't be resolved generically. - Type-mismatch restoration is silent. If a key survives an edit but its value's
typeofchanges (e.g. a number becomes an object), the old value is dropped without a console warning. State simply resets for that key with no explicit signal as to why. - Any unhandled exception during patch/reconcile falls back to a full page reload, per the process flow above — this is the ultimate safety net for cases the above heuristics don't cover.
📋 API Reference
pawajsPlugin(): Plugin
Vite plugin that transforms PawaJS component files.
No configuration options needed - works out of the box.
pawaHMR(): Plugin
Vite plugin that enables HMR for PawaJS components and utilities.
HMR Event Data
When a PawaJS file changes, a custom event is sent with the following structure:
interface PawaHMRCustomEventData {
file: string | null // URL of the first changed module
files: string[] // All changed module URLs
kind: 'component' | 'util' // Type of change
isComponent: boolean
isUtil: boolean
modules: Array<{ // Module metadata
url: string
id: string
importers: string[]
}>
timestamp: number // Time of change
}Note: The HMR client (src/reload.js) is automatically injected and handles most component updates for you. Component re-rendering and module re-importing are done automatically.
📄 License
This project is licensed under the MIT License.
