Skip to content

Commit

Permalink
Vite: Fix HMR issue for Storybook preview files
Browse files Browse the repository at this point in the history
  • Loading branch information
valentinpalkovic committed May 23, 2024
1 parent 480374a commit 525bd60
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions code/builders/builder-vite/src/codegen-modern-iframe-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ export async function generateModernIframeScriptCode(options: Options, projectRo
// and the HMR handler. We don't use the hot.accept callback params because only the changed
// modules are provided, the rest are null. We can just re-import everything again in that case.
const getPreviewAnnotationsFunction = `
const getProjectAnnotations = async () => {
const getProjectAnnotations = async (hmrPreviewAnnotationModules = []) => {
const configs = await Promise.all([${previewAnnotationURLs
.map((previewAnnotation) => `import('${previewAnnotation}')`)
.map(
(previewAnnotation, index) =>
// Prefer the updated module from an HMR update, otherwise import the original module
`hmrPreviewAnnotationModules.at(${index}) ?? import('${previewAnnotation}')`
)
.join(',\n')}])
return composeConfigs(configs);
}`;
Expand All @@ -45,10 +49,10 @@ export async function generateModernIframeScriptCode(options: Options, projectRo
window.__STORYBOOK_PREVIEW__.onStoriesChanged({ importFn: newModule.importFn });
});
import.meta.hot.accept(${JSON.stringify(previewAnnotationURLs)}, () => {
import.meta.hot.accept(${JSON.stringify(previewAnnotationURLs)}, (previewAnnotationModules) => {
${getPreviewAnnotationsFunction}
// getProjectAnnotations has changed so we need to patch the new one in
window.__STORYBOOK_PREVIEW__.onGetProjectAnnotationsChanged({ getProjectAnnotations });
window.__STORYBOOK_PREVIEW__.onGetProjectAnnotationsChanged({ getProjectAnnotations: () => getProjectAnnotations(previewAnnotationModules) });
});
}`.trim();
};
Expand Down

0 comments on commit 525bd60

Please sign in to comment.