Preact router not working after Parcel build

112 views Asked by At

I setup a project with parcel that with a preact app. When running the project with as dev with npm run dev (It allow me to test at http://localhost:8080). When I access to http://localhost:8080 and click on My Profile link it works fine.

But when I build the project with npm run build (cf package.json) and serve the build file in dist/index.html and then I acces to http://localhost:8080/profile then the router is not working (404)

index.js

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

const Home = ()=> (<h2>Home</h2>);
const MyProfile = () => <h2>My Profile</h2>;

function App() {
  return (
    <div>
      <nav>
        <a href="/">Home</a>
        <a href="/profile">My Profile</a>
      </nav>
      <br></br>
      <Router>
        <Home path="/" />
        <MyProfile path="/profile" />
      </Router>
    </div>
  );
}

render(<App />, document.body);

package.json

{
  "name": "test-preact-router",
  "version": "1.0.0",
  "description": "",
  "source": "index.html",
  "scripts": {
    "dev": "npx parcel -p 8080",
    "build": "npx parcel build"
  },
  "alias": {
    "preact/jsx-dev-runtime": "preact/jsx-runtime"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "parcel": "^2.9.3",
    "preact": "^10.15.1",
    "preact-router": "^4.1.1"
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="container"></div>
  <script type="module" src="./index.js"></script>
</body>
</html>

Visiting http://localhost:8080/profile should be working

1

There are 1 answers

0
rschristian On BEST ANSWER

In all likelihood you've not properly configured your server for the built files.

For SPAs, you will need to route every request to /index.html. Your server is likely 404'ing on not finding /profile.html to serve when you request /profile. How you configure this depends on the server you're using, which you don't specify.