Remove hmr accept calls from story files

This commit is contained in:
Ian VanSchooten 2022-08-26 17:45:00 -04:00
parent 9647bf2d23
commit b2f61d7826
2 changed files with 29 additions and 0 deletions

View File

@ -0,0 +1,27 @@
import type { Plugin } from 'vite';
import { createFilter } from 'vite';
import MagicString from 'magic-string';
/**
* This plugin removes HMR `accept` calls in story files. Stories should not be treated
* as hmr boundaries, but vite has a bug which causes them to be treated as boundaries
* (https://github.com/vitejs/vite/issues/9869).
*/
export function stripStoryHMRBoundary(): Plugin {
const filter = createFilter(/\.stories\.([tj])sx?$/);
return {
name: 'storybook:strip-hmr-boundary',
enforce: 'post',
async transform(src: string, id: string) {
if (!filter(id)) return undefined;
const s = new MagicString(src);
s.replace(/import\.meta\.hot\.accept\(\);/, '');
return {
code: s.toString(),
map: s.generateMap({ hires: true, source: id }),
};
},
};
}

View File

@ -14,6 +14,7 @@ import { stringifyProcessEnvs } from './envs';
import { injectExportOrderPlugin } from './inject-export-order-plugin';
import { mdxPlugin } from './plugins/mdx-plugin';
import { noFouc } from './plugins/no-fouc';
import { stripStoryHMRBoundary } from './plugins/strip-story-hmr-boundaries';
import type { ExtendedOptions, EnvsRaw } from './types';
export type PluginConfigType = 'build' | 'development';
@ -89,6 +90,7 @@ export async function pluginConfig(options: ExtendedOptions) {
mdxPlugin(options),
noFouc(),
injectExportOrderPlugin,
stripStoryHMRBoundary(),
] as PluginOption[];
// We need the react plugin here to support MDX in non-react projects.