Skip to content

Commit

Permalink
Fix svelte story files not reloading (#362)
Browse files Browse the repository at this point in the history
Fixes #52

Svelte story files have the same issue as react story files.  The webpack HMR seems to prevent vite's HMR from working correctly, so we need to exclude story files as HMR boundaries in vite.  The svelte plugin doesn't expose as nice of a way to do this, but thanks to a suggestion from @domyen in sveltejs/vite-plugin-svelte#321 (comment), I was able to make it work.

To test:
Start up the svelte example, edit a `.stories.svelte` file, and confirm that the page reloads and shows your changes.
  • Loading branch information
IanVS authored May 1, 2022
1 parent 8eaec13 commit 3b71dcd
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions packages/builder-vite/vite-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export async function commonConfig(

export async function pluginConfig(options: ExtendedOptions, _type: PluginConfigType) {
const { framework, presets } = options;
const svelteOptions = await presets.apply('svelteOptions', {}, options);
const svelteOptions: Record<string, any> = await presets.apply('svelteOptions', {}, options);

const plugins = [
codeGeneratorPlugin(options),
Expand Down Expand Up @@ -82,7 +82,27 @@ export async function pluginConfig(options: ExtendedOptions, _type: PluginConfig
if (framework === 'svelte') {
try {
const sveltePlugin = require('@sveltejs/vite-plugin-svelte').svelte;
plugins.push(sveltePlugin(svelteOptions));

// We need to create two separate svelte plugins, one for stories, and one for other svelte files
// because stories.svelte files cannot be hot-module-reloaded.
// Suggested in: https://github.com/sveltejs/vite-plugin-svelte/issues/321#issuecomment-1113205509

// First, create an array containing user exclude patterns, to combine with ours.
const userExclude = Array.isArray(svelteOptions?.exclude)
? svelteOptions?.exclude
: svelteOptions?.exclude
? [svelteOptions?.exclude]
: [];

// These are the svelte stories we need to exclude from HMR
const storyPatterns = ['**/*.story.svelte', '**/*.stories.svelte'];
// Non-story svelte files
plugins.push(sveltePlugin({ ...svelteOptions, exclude: [...userExclude, ...storyPatterns] }));
// Svelte stories without HMR
plugins.push({
...sveltePlugin({ ...svelteOptions, exclude: userExclude, include: storyPatterns, hot: false }),
name: 'vite-plugin-svelte-stories',
});
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {
throw new Error(
Expand Down

0 comments on commit 3b71dcd

Please sign in to comment.