preactjs / preact-router

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

Accessing the link from the router directly on after Parcel build is not working #451

Closed andrianina-oelimahefason closed 1 year ago

andrianina-oelimahefason commented 1 year ago

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>
rschristian commented 1 year ago

In all likelihood you haven't set up SPA routing in whatever server you're testing your built files in. You need to make sure all requests are redirected to /index.html.