preact-markup icon indicating copy to clipboard operation
preact-markup copied to clipboard

ReferenceError: document is not defined. Server Side rendering does not seem to work.

Open insipidish opened this issue 9 years ago • 2 comments

Hi

I am trying to use the Markup component while rendering server side with preact-render-to-string.
I get the following error: 'ReferenceError: document is not defined'

Could you suggest a work around?

insipidish avatar Sep 16 '16 02:09 insipidish

Ah yeah that's a good point. This uses the browser's built-in DOM parser, which isn't available under node. Should be possible to detect node and require() in a simple parser lib though! Will need to update the code :)

developit avatar Sep 16 '16 03:09 developit

Preact WMR injects a NodeJS DOMParser for static SSR (aka "prerender"):

globalThis.DOMParser = new (require('jsdom').JSDOM)('').window.DOMParser;

https://github.com/preactjs/wmr/blob/7077053172e4ef347397cdde375c806ab8f32d8e/docs/public/prerender.js#L6-L12

(PR context: https://github.com/preactjs/wmr/pull/497/files )

This way, this never fails:

https://github.com/developit/preact-markup/blob/4788b8d61b4e24f83688710746ee36e7464f7bbc/src/parse-markup.js#L22-L26

...and this iframe-based fallback never gets called in the html case:

https://github.com/developit/preact-markup/blob/4788b8d61b4e24f83688710746ee36e7464f7bbc/src/parse-markup.js#L60-L69

Related PRs:

https://github.com/developit/preact-markup/pull/24

https://github.com/developit/preact-markup/pull/22

https://github.com/developit/preact-markup/pull/40

https://github.com/developit/preact-markup/pull/18

danielweck avatar Mar 30 '21 05:03 danielweck