preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.02k stars 155 forks source link

createHashHistory - build error - Preact-CLI #377

Closed rajatdua closed 2 years ago

rajatdua commented 4 years ago

I was testing Preact and wanted to check hash history routing. I followed the following JS Fiddle from developit about how to implement hash-routing.

The problem comes down when I run npm run build passing history prop in Router - createHashHistory() causes build error with the following error message -

ReferenceError: document is not defined
method: null
at: undefined:null:null

Source code:

✖ ERROR TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer. Received undefined
    at validChunk (_stream_writable.js:281:10)
    at WriteStream.Writable.write (_stream_writable.js:316:21)
    at handlePrerenderError (/Users/rajatdua/Documents/Projects/Preact/node_modules/preact-cli/lib/lib/webpack/prerender.js:111:18)

Code for reference -

App.js

<Router history={createHashHistory()} onChange={this.handleRoute}>
      <Home path="/" />
      <Profile path="/profile/" user="me" />
      <Profile path="/profile/:user" />
</Router>

Nav.js

<nav>
      <Link activeClassName={style.active} href='/'>Home</Link>
      <Link activeClassName={style.active} href='/profile'>Me</Link>
      <Link activeClassName={style.active} href='/profile/john'>John</Link>
</nav>

I used the same version for the libraries mentioned in the fiddle and also tried with the latest versions too.

JS Fiddle

  "dependencies": {
    "history": "^4.6.1",
    "preact": "^10.4.7",
    "preact-render-to-string": "^5.1.4",
    "preact-router": "^3.2.1",
  },

New Versions

  "dependencies": {
    "history": "^5.0.0",
    "preact": "^10.4.7",
    "preact-render-to-string": "^5.1.10",
    "preact-router": "^3.2.1",
  }

Preact-CLI versions, which I tested on

"preact-cli": "^3.0.0", "preact-cli": "^3.0.1",

rajatdua commented 4 years ago

As it's hash-router I'm not sure if it will work with pre-rendering - SSR.

    "build": "APP_ENV=production preact build",

P.S: The build script which I used for npm run build

rschristian commented 2 years ago

Yes, hash routers only work in the browser. Preact-CLI prerenders your app in Node, therefore they're not really compatible.

You can get around this by dropping out of prerendering or using window checks (see https://github.com/preactjs/preact-cli#pre-rendering). However, without the router being available, there's likely little value in prerendering.