Thanks! You put me back on the right track, it was indeed an Astro-specific issue. Wouldn’t you know it that the thing that works for 99% of Astro users, did not work for my setup.
As it turns out because I’m writing my site with MDX files, the babylon.js sketches are dynamically loaded and specific to each page. Astro’s built-in script handling forces inline scripts when passing variables like filenames or paths, which breaks Vite’s module bundling capabilities. (Scripts and Event Handling | Docs)
As a workaround, Astro makes it easy to use React as middleware, which avoids this limitation , allowing Vite to properly bundle the scripts and modules.
Now it works both in dev mode and in build-preview mode, and the final problem to solve is how to set this thing up so it works both in build mode and also on gh-pages, which have a sub-path issue to deal with.
https://github.com/rdthree/astro-rd3-sketchbook/blob/master/src/components/SketchLoader.jsx