preactjs / preset-vite

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

Feat: Better prerender errors #107

Closed rschristian closed 9 months ago

rschristian commented 9 months ago

Closes #106

Full example:

$ npm run build

> build
> vite build

vite v5.1.3 building for production...
✓ 19 modules transformed.
x Build failed in 316ms
error during build:
RollupError: [preact:prerender]

ReferenceError: document is not defined

This is most likely caused by using DOM/Web APIs which are not available
available to the prerendering process running in Node. Consider
wrapping the offending code in a window check like so:

if (typeof window !== "undefined") {
    // do something in browsers only
}

> /home/ryun/Projects/my-preact-app/src/index.jsx:22:18

  20 | }
  21 |
> 22 | hydrate(<App />, document.getElementById('app'));
     |                  ^
  23 |
  24 | export async function prerender(data) {
  25 |  return await ssr(<App {...data} />);

    at getRollupEror (file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/parseAst.js:375:41)
    at error (file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/parseAst.js:372:42)
    at Object.error (file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/node-entry.js:19394:20)
    at Object.generateBundle (file:///home/ryun/Projects/my-preact-app/node_modules/@preact/preset-vite/dist/esm/prerender.mjs:207:22)
    at async Bundle.generate (file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/node-entry.js:17947:9)
    at async file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/node-entry.js:20494:27
    at async catchUnfinishedHookActions (file:///home/ryun/Projects/my-preact-app/node_modules/rollup/dist/es/shared/node-entry.js:19923:16)
    at async build (file:///home/ryun/Projects/my-preact-app/node_modules/vite/dist/node/chunks/dep-stQc5rCc.js:66902:22)
    at async CAC.<anonymous> (file:///home/ryun/Projects/my-preact-app/node_modules/vite/dist/node/cli.js:842:9)

Certainly let me know if anyone wants to see more, less, etc.

The stack trace isn't super useful, but it comes from Rollup's this.emit() -- I don't think it's worth messing with.

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.