preactjs / preact-router

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

Hash routing breaks build #414

Closed Dave3of5 closed 2 years ago

Dave3of5 commented 2 years ago

Hash routing as explained on the readme.md breaks the build:

Source code:

✖ ERROR TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
    at new NodeError (node:internal/errors:371:5)
    at _write (node:internal/streams/writable:312:13)
    at WriteStream.Writable.write (node:internal/streams/writable:334:10)
    at handlePrerenderError (/Users/davidkolosowski/test/node_modules/preact-cli/lib/lib/webpack/prerender.js:110:18)

Create a new default app:

npx preact-cli create default my-project

Add history package:

npm install --save history

Add following to app.js:

import { h } from 'preact';
import { Router } from 'preact-router';

import Header from './header';

// Code-splitting is automated for `routes` directory
import Home from '../routes/home';
import Profile from '../routes/profile';
import { createHashHistory  } from 'history';

const App = () => (
    <div id="app">
        <Header />
        <Router history={createHashHistory()}>
            <Home path="/" />
            <Profile path="/profile/" user="me" />
            <Profile path="/profile/:user" />
        </Router>
    </div>
)

export default App;

Run build:

npm run build

Build crashes.

rschristian commented 2 years ago

This is correct behavior. If you'll take a look at the full error (it looks like you cut off the first few lines), you'll see:

ReferenceError: document is not defined

Hash routers depend on the DOM, which is unavailable when prerendering as this happens in Node.

You can opt out of prerendering in preact-cli with the --no-prerender flag, see: preact-cli#pre-rendering

Dave3of5 commented 2 years ago

Excellent thanks for that answer @rschristian. Maybe just needs the README updated then to include this.