CleverCloud / clever-components

Collection of Web Components by Clever Cloud
https://www.clever-cloud.com/doc/clever-components/
Apache License 2.0
215 stars 19 forks source link

Storybook/vite: error when HMR is triggered while browsing `demo-smart` / `sandbox` (anything but Storybook) #1026

Closed florian-sanders-cc closed 2 months ago

florian-sanders-cc commented 2 months ago

Context

With #991, we introduced HMR for component docs.

This works well but it triggers an error when a file is modified while browsing demo-smart / sandbox (anything but Storybook). We get the following error:

Cannot read properties of undefined (reading 'invalidationState')
    at ModuleGraph.invalidateModule (.../clever-components/node_modules/vite/dist/node/chunks/dep-B-u6xNiR.js:64130:43)
    at handleHotUpdate (.../clever-components/cem/generate-cem-vite-plugin.js:44:28)
    at handleHMRUpdate (.../clever-components/node_modules/vite/dist/node/chunks/dep-B-u6xNiR.js:65191:39)
    at async onHMRUpdate (.../clever-components/node_modules/vite/dist/node/chunks/dep-B-u6xNiR.js:64719:17)
    at async FSWatcher.<anonymous> (.../Projects/clever-components/node_modules/vite/dist/node/chunks/dep-B-u6xNiR.js:64756:9

This happens because:

  1. the handleHotUpdate hook of the generate-cem-vite-plugin is called everytime a hot update is about to happen,
  2. within this hook, we test if the path related to the hot update is a component file (which is true),
  3. we invalidate the CEM virtual module but it does not exist, we're outside of Storybook here so the CEM is not imported by anything (no story, no storybook UI, no docs).

Solution

Do not invalidate the CEM virtual module if the module is undefined.