reactjswebpackreact-routerreact-router-domwebpack-5

Webpack 5 + React Router v6 - Blank Page on Build


For some reason, when I use npm run serve, I can access my page just fine and the routes work as they are supposed to. However, when I use npm run build, I encounter a white screen even if I correct my asset directories. What am I doing wrong?

// App.tsx
import { Routes, Route, BrowserRouter } from 'react-router-dom';

/**
 * Application entry point.
 *
 * @return {JSX.Element}
 */
const App: () => JSX.Element = (): JSX.Element => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<h1>Hello world!</h1>} />
        <Route path="/add" element={<h1>Hello add!</h1>} />
      </Routes>
    </BrowserRouter>
  );
};

export default App;

I created a breakaway branch to isolate the issue and leave out any unnecessary code: https://bitbucket.org/blackboardd/shoppy/src/breakaway-for-router/.

If anyone wants to try running it:

git clone -b breakaway-for-router git@bitbucket.org:blackboardd/shoppy.git
cd shoppy
npm install

// This works fine.
npm run serve

// This has a blank white screen when the index.html file is opened, even with the asset directories corrected for local viewing.
npm run build

System Information: Visual Studio Code on Remote WSL 2 Windows 11 Version 21H2


Solution

  • I had two issues.

    Problem #1: Bad production build testing.

    I should have been testing it with a web server. What I ended up using was a globally installed serve package and running serve -s dist. This ended up giving me working routes. The only thing I modified about my TypeScript files was importing Route and Routes from react-router-dom where I was previously importing them from react-router, but I'm not sure if that had any meaningful effect.

    So one of the things I made sure to do was add this line into my webpack.prod.js file:

      output: {
        publicPath: '/',
      },
    

    Problem #2: 404 error on routes other than /.

    then I was having an issue with my redirects. I needed a _redirects file in my distribution:

    /* /index.html 200
    

    I also used the copy-webpack-plugin to move the file from public to dist. This is the snippet for that portion:

      plugins: [
        // ...
        new CopyPlugin({
          patterns: [
            {
              from: 'public/_redirects',
              to: '.',
            },
          ],
        })
      ],