vite-plugin-stimulus-hmr
Version:
HMR for Stimulus controllers in Vite.js, tweak your JS without refreshing the page.
44 lines (43 loc) • 1.54 kB
JavaScript
// src/index.ts
import { identifierForGlobKey } from "stimulus-vite-helpers";
import createDebugger from "debug";
var debug = createDebugger("stimulus:hmr");
function StimulusHMRPlugin({ appGlobal = "$$StimulusApp$$" } = {}) {
return {
name: "stimulus:hmr",
apply: "serve",
transform(code, id, options) {
if ((options == null ? void 0 : options.ssr) && !process.env.VITEST || id.includes("node_modules"))
return;
const appRegex = /\n[^\n]*?\s(\w+)(?:\s*=\s*Application\.start\(\))/;
const appVariable = (code.match(appRegex) || [])[1];
if (appVariable) {
debug("application", { appVariable, id });
const exportFooter = `export const $$StimulusApp$$ = window.$$StimulusApp$$ = ${appVariable};`;
return `${code}
${exportFooter}`;
}
const controllerId = identifierForGlobKey(id);
if (!controllerId)
return;
debug("controller", { name: controllerId, id });
const metaHotFooter = `
if (import.meta.hot) {
import.meta.hot.accept(newModule => {
if (!window.${appGlobal}) {
console.warn('Stimulus app not available. Are you creating the app? Falling back to page refresh.');
import.meta.hot.invalidate();
} else {
window.${appGlobal}.register('${controllerId}', newModule.default);
}
})
}
`.replace(/(\n|\s\s)+/gm, "");
return `${code}
${metaHotFooter}`;
}
};
}
export {
StimulusHMRPlugin as default
};