Issue with building Webpack React Router DOM configuration

I recently developed a React+Typescript app with Webpack 5 configuration completely from scratch. Everything was running smoothly in development mode, and I utilized React Router DOM version 6.23.1 for routing. However, once I built the app, some components failed to display without any error messages in the console. This issue specifically affects components nested inside <Route> tags. Interestingly, when I moved the <Home> component outside of the <Routes> tag, it appeared on the screen as expected.

Despite trying various solutions like downgrading React Router DOM and adding

"homepage": "."
to package.json, the issue persists.

index.tsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

const rootElement = document.getElementById("root");

const root = createRoot(rootElement!);

root.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
);

App.tsx

import { Route, Routes } from "react-router-dom";
import GlobalStyle from "./globalStyles";
import { ApolloProvider } from "@apollo/client";
import { RecoilRoot } from "recoil";
import { Layout } from "./components/Layout";
import { Home } from "./components/pages/Home";
import { client } from "./lib/data";
import { Favorites } from "./components/pages/Favorites";
import { Tours } from "./components/pages/Tours";
import { About } from "./components/pages/About";

export default function App() {
  return (
    <main>
      <GlobalStyle />
      <RecoilRoot>
        <ApolloProvider client={client}>
          <Routes>
            <Route path="/" element={<Layout />}>
              <Route index element={<Home />} />
              <Route path="favorites" element={<Favorites />} />
              <Route path="tours" element={<Tours />} />
              <Route path="about" element={<About />} />
            </Route>
          </Routes>
        </ApolloProvider>
      </RecoilRoot>
    </main>
  );
}

webpack.config.ts

import path from "path";
import { Configuration } from "webpack";
import CopyWebpackPlugin from "copy-webpack-plugin";
import "webpack-dev-server";

const config: Configuration = {
  entry: "./src/index.tsx",
  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
    publicPath: "/",
  },
  devServer: {
    historyApiFallback: true,
    static: {
      directory: path.resolve(__dirname, "dist"),
    },
    compress: true,
    port: 8080,
  },
  plugins: [
    new CopyWebpackPlugin({
      patterns: [{ from: "public" }],
    }),
  ],
};

export default config;

tsconfig.json

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "noImplicitAny": true,
    "target": "es5",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "./dist/",
    "moduleResolution": "node"
  },
  "include": ["**/*.ts", "**/*.tsx"]
}

Answer №1

If you are encountering this same problem, I found a solution by creating a file called vercel.json:

{
  "rewrites": [{ "source": "/(.*)", "destination": "/" }]
}

In addition, I discovered that I had forgotten to specify the Output directory in Vercel's Build & Development Settings. In my case, it needed to be named dist.

https://i.sstatic.net/LRMyCf4d.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Is it possible to automatically correct all import statements in a TypeScript project?

After transferring some class member variables to a separate class in another file, I realized that these variables were extensively used in the project. As a result, approximately 1000 .ts files will need their imports modified to point to the new class/f ...

What are the best methods for repairing a malfunctioning Drawer?

My template can be found here: SANDBOX When transitioning to a nested route, I am experiencing a double rendering issue which causes the DRAWER to reopen. How can this be fixed? You can observe this effect in the "NESTED" tab. It is important that the fi ...

Unable to retrieve headers from extended Express.Request type

Currently, I am attempting to enhance the Request in Express so that it accurately represents the structure of a query. My current approach is as follows: export interface TypedRequestQuery<T> extends Express.Request { query: T; } While this met ...

TypeScript's reliance on dependent types

Is it possible to implement this functionality using TypeScript? There exist objects that define various "actions". export interface IAction { action: string; data: any; otherParam1: number; otherParam2: number; } The 'action' p ...

Verifying Whether Objects in TypeScript File Adhere to a Certain Interface

Currently, I am in the process of developing a procedure that scans through a collection of *.ts files within a directory to identify those containing a class that implements a specific interface. While my preference is to be able to detect multiple classe ...

How to toggle visibility of child elements in an HTML template using Angular 4+

I'm currently working on incorporating a basic "hover over a comment to display a reply button" feature in my angular application. Is it possible to create this effect using template reference variables exclusively? Something like this... <mat-l ...

Reasons behind Angular HttpClient sorting JSON fields

Recently, I encountered a small issue with HttpClient when trying to retrieve data from my API: constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get("http://localhost:8080/api/test/test?status=None").subscribe((data)=> ...

Tips for maintaining selected text while a modal window is active

So I'm currently working on a document writer and I'm utilizing document.execCommand to insert links. What I aim for is the ability for a user to select/highlight text, click a button to add a link to that specific text (via a modal), and then ha ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

The content security policy is preventing a connection to the signalr hub

Currently, I am developing an application using electron that incorporates React and Typescript. One of the features I am integrating is a SignalR hub for chat functionality. However, when attempting to connect to my SignalR server, I encounter the followi ...

React Navigation - CSS file identified as "text/html" after introducing a dynamic route parameter (/userId)

Our customized stylesheet "styles.css" seems to be incorrectly identified with the MIME type "text/html", even though it is specified as: rel="stylesheet" type="text/css" This issue only arises when navigating to routes with a variable parameter such as ...

Failed to complete the build process due to webpack errors encountered while running the async Object.build

After updating my Next.js app from version 9 to 11, I encountered an error related to webpack. Despite upgrading webpack to version 5, the build process failed with webpack errors. Here is the error message: > Build error occurred Error: > Build fail ...

Show information from the state using React and Typescript

I successfully retrieved data from an API using axios and stored it in the state of my React component. However, I am struggling to display this data on the web so that I can list all the information obtained from the API request. I have tried using the ma ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...

Steps for Signing Up for a Collaboration Service

I'm struggling to understand how to monitor for new values in an observable from a service. My ultimate objective is to integrate an interceptor, a service, and a directive to show loading information to the user. I have set up an interceptor to liste ...

tslint: no use of namespace and module is permitted

I have recently acquired a legacy .ts file that I would like to update. Two warnings appear: 'namespace' and 'module' are disallowed and The internal 'module' syntax is deprecated, use the 'namespace' keyword ins ...

What is the process of this script when initiated with an NPM build command?

I have a package.JSON file with the following scripts: "scripts": { "typings": "typings install", "build": "tsc && webpack", "watch": "npm-run-all -p -r -l tsc-watch webpack-watch", "tsc-watch": "tsc -w", "webpack-watch": "web ...

The function signature '(event: ChangeEvent<HTMLInputElement>) => void' does not match the expected type 'ChangeEvent<HTMLInputElement>'

This is my first time using TypeScript to work on a project from the ZTM course, which was initially written in JavaScript. I am facing an issue where I am unable to set a type for the event parameter. The error message I receive states: Type '(event: ...