developit / preact-markup

:zap: Render HTML5 as VDOM, with Components as Custom Elements!
http://npm.im/preact-markup
MIT License
201 stars 30 forks source link

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

Open insipidish opened 8 years ago

insipidish commented 8 years ago

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?

developit commented 8 years ago

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 :)

danielweck commented 3 years ago

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