Skip to content

Commit

Permalink
refactor: centralise module script injection
Browse files Browse the repository at this point in the history
  • Loading branch information
fwouts committed Aug 26, 2023
1 parent 0c5bac8 commit 2b01334
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 17 deletions.
22 changes: 12 additions & 10 deletions core/src/vite/vite-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,19 @@ export class ViteManager {
: null;
return await viteServer.transformIndexHtml(
url,
template.replace(/%([^%]+)%/gi, (matched) => {
switch (matched) {
case "%INIT_PREVIEW_BLOCK%":
return `
template.replace(
"%MODULE_SCRIPT%",
`
import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
initListeners();
import.meta.hot.accept();
let latestPreviewableModule;
let latestWrapperModule;
let refresh;
import.meta.hot.accept(["/${componentPath}"], ([previewableModule]) => {
if (previewableModule && refresh) {
latestPreviewableModule = previewableModule;
Expand Down Expand Up @@ -120,11 +125,8 @@ export class ViteManager {
});
});
});
`;
default:
throw new Error(`Unknown template key: ${matched}`);
}
})
`
)
);
}

Expand Down
8 changes: 1 addition & 7 deletions iframe/preview/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,7 @@
window.module = undefined;
</script>
<script type="module">
import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";

initListeners();

import.meta.hot.accept();

%INIT_PREVIEW_BLOCK%
%MODULE_SCRIPT%
</script>
<style>
body {
Expand Down

0 comments on commit 2b01334

Please sign in to comment.