preactjs / preset-vite

Preset for using Preact with the vite bundler
https://npm.im/@preact/preset-vite
MIT License
259 stars 26 forks source link

refactor: Clean sourcemaps in newer Vite versions #109

Closed rschristian closed 6 months ago

rschristian commented 6 months ago

Unfortunately there's no way for us to clean up the source maps, and we need to enable them for all users running the prerender. Vite doesn't add them to the bundle, so we can't simply delete them, and it looks like they're written post writeBundle(), leaving us without much in the way of options to clean up after ourselves. Even if we could find a way, Vite would still likely include them in the output message which would be a bit wonky if they were then to not be there.

Turns out this is incorrect, and in Vite v4.0.0+, source maps are available in the bundle (via generateBundle() &writeBundle()) AND no longer shown as separate assets in the output message, meaning they're easy to clean up and shouldn't be a source of confusion if they are stripped.

For context, here's the output message for the demo running Vite v2 in this repo and a new project running Vite v5.

v2 v4+
✓ 22 modules transformed.
dist/assets/preact.48177e6f.svg     1.55 KiB
dist/index.html                     1.64 KiB
dist/404/index.html                 0.79 KiB
dist/assets/index.d54d9340.js       0.73 KiB / gzip: 0.42 KiB
dist/assets/index.d54d9340.js.map   2.51 KiB
dist/assets/prerender.488e3408.js   5.66 KiB / gzip: 2.73 KiB
dist/assets/prerender.488e3408.js.map 14.21 KiB
dist/assets/index.903e2b44.css      1.39 KiB / gzip: 0.64 KiB
dist/assets/index.2b362f5c.js       24.58 KiB / gzip: 9.80 KiB
dist/assets/index.2b362f5c.js.map   77.04 KiB
✓ 19 modules transformed.
dist/404/index.html                 0.75 kB │ gzip: 0.44 kB
dist/index.html                     3.39 kB │ gzip: 1.57 kB
dist/assets/index-lsHz2dNc.css      1.42 kB │ gzip: 0.66 kB
dist/assets/index-DaLm86T7.js       0.78 kB │ gzip: 0.46 kB │ map:  0.10 kB
dist/assets/prerender--qygTkgT.js   6.41 kB │ gzip: 3.08 kB │ map: 18.22 kB
dist/assets/index-DkHoFdfI.js      21.78 kB │ gzip: 9.01 kB │ map: 60.56 kB

So if the user is running a newer version of Vite, and hasn't enabled sourcemaps themselves, we'll strip them out of the bundle during the prerendering process so that we can use them but they don't end up in the output files. We are still left with the │ map: 18.22 kB bit, but I don't think that's likely to cause any confusion.

In older versions of Vite, there's no effect, as the sourcemaps aren't available in the bundle.