Skip to content

Commit

Permalink
Merge pull request #27256 from storybookjs/valentin/fix-hmr-issue-in-…
Browse files Browse the repository at this point in the history
…preview

Vite: Fix HMR issue for Storybook preview files
(cherry picked from commit 6c04751)
  • Loading branch information
valentinpalkovic authored and storybook-bot committed May 27, 2024
1 parent a2b9d08 commit 8264edd
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 8264edd

Please sign in to comment.