The historyApiFallback feature in webpack-dev-server does not seem to function properly when dealing with multi-level routing scenarios

Currently, I have set historyApiFallback: true to redirect any non-existing URLs to the index page. It works perfectly for first-level routes like localhost:8080/abc. However, when attempting localhost:8080/abc/xyz, an error appears in the browser console:

http://localhost:8080/abc/scripts/bundle.js 404 (Not Found)

This is my Webpack config:

const path = require('path');

module.exports = {
    entry:"./src/app.js",
    output:{
        path:path.join(__dirname,'public','scripts'),
        filename:'bundle.js'
    },
    module:{
        rules:[{
            test:/\.js$/,
            exclude:/node_modules/,
            loader:'babel-loader'
        }]
    },
    devServer:{
        contentBase:path.join(__dirname,'public'),
        publicPath:'/scripts/',
        historyApiFallback: true
    }
}

Below is the structure of the index page:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div id="app">
        hello
    </div>
</body>
<script type="text/javascript" src="scripts/bundle.js"></script>
</html>

The folder structure looks like this:

-node_modules/
-public/
    -scripts/
    -index.html
-src/
    -app.js
-package.json
-webpack.config.js

Can anyone see what might be missing here?

Answer №1

The issue with the script tag in the HTML code was due to a missing forward slash. I found a helpful solution here which resolved the problem.

Answer №2

To enhance the behavior even more, you have the option to utilize rewrites. As stated in the provided documentation:

historyApiFallback: {
  rewrites: [
    { from: /^\/$/, to: '/views/landing.html' },
    { from: /^\/subpage/, to: '/views/subpage.html' },
    { from: /./, to: '/views/404.html' }
  ]
}

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

Struggling with TypeScript tests elusive to Jest

I'm encountering a strange error while attempting to write a jest test. TypeError: jest_1.it is not a function 9 | 10 | describe('Health check', () => { > 11 | it('GET works', async () => { Instead of displayi ...

Dealing with Dependency Injection Problem in Angular 6

I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it: @NgModule({ providers: [ ...

Restrict the keys to only properties that have an array data type

Is there a way to limit the keyof operator to only accept keys of a specified type in TypeScript? interface Data { items: string[]; name: string; } // I want to restrict the keyof operator to only allow keys where the value is of type `F` type Key&l ...

Is it possible to modify the number format of an input field while in Antd's table-row-edit mode?

I am currently utilizing the Table Component of Ant Design v2.x and unfortunately, I cannot conduct an upgrade. My concern lies with the inconsistent formatting of numbers in row-edit mode. In Display mode, I have German formatting (which is desired), but ...

In Typescript, an index signature parameter can only be of type 'string' or 'number'

I'm facing an issue with a generic type that defaults to string: interface EntityState<typeOfID = string> { entities: { [ id: typeOfID]: any }; } The error I receive is: An index signature parameter type must be either 'string' or ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

Setting the default selected row to the first row in ag-Grid (Angular)

Is there a way to automatically select the first row in ag-grid when using it with Angular? If you're curious, here's some code that may help: https://stackblitz.com/edit/ag-grid-angular-hello-world-xabqct?file=src/app/app.component.ts I'm ...

Error: The method that is annotated with @action in MobX is not defined

I'm encountering a peculiar problem with the MobX annotations, where a method marked with @action seems to be missing from the resulting object. Let's consider the following TypeScript code snippet as a basic example: export class Car { @ob ...

Issue: TypeScript does not allow assigning a boolean type to either true or false when using two interfaces

When utilizing code similar to the one below, one would assume that TypeScript could infer that badObj is a valid argument for fn, as it should have the type Bad. Interestingly, within the body of fn there seems to be no issue. However, when calling fn(ba ...

Angular version 5 consistently replaces the chosen date with the current date

Currently facing an issue with an input field that contains a date. Whenever a date is selected that is not today's date, it always defaults to the current date and gets saved in the backend. I need the selected date to be saved instead. The console l ...

What is the best way to generate a unique UUID for every object created within a loop?

I am working on a typescript method that eliminates hashtags from a string and saves them in an array within a model. Each element in the hashtag array is assigned a unique UUID along with the complete string added to the model. However, I am facing an iss ...

Is there a way to define a variable of type Express in TypeScript without the need to import the express

One approach I am considering is to have a main.ts file where I import express just once using the following line of code: import express from 'express'; In another separate file, let's say a class where I want to define a method called "in ...

Instruct the user to input a file name before initiating the download of a text file using Angular

Does anyone have experience with downloading content in a txt file? Here is the code snippet I'm working with: download() { let content = "Sample text"; saveAs(new Blob([content], { type: 'text/plain'}), 'sample.txt'); I am usi ...

The array is filled with values, however, there seems to be an issue preventing their access. What could possibly be causing this obstacle

After receiving two string values through a callback function, let's call them a and b, I attempt to store them in an array. However, when I check the array using console.log, it only displays the values if I expand the array by clicking on the arrow ...

Having trouble locating the module - Nuxt 3, TypeScript

Encountering an issue while attempting to import a .ts file in 'nuxt.config.ts' using the paths '@/' and '~/'. The error message reads: Cannot find module '~/path', Require stack: - nuxt.config.ts at Module._resolveF ...

When utilizing a 'Token' in the provider() aliasing within Angular 2, the Typescript compiler may display an error message stating 'Unresolved variable or type'. This issue can arise when defining

When working with Typscript, I've encountered an issue where it can't handle a 'Token' in the context of an Angular2 provide() aliasing function. I'm unsure if there's a specific setting in the typescript compiler to address t ...

Serializing a mixed-type array

I have an array in TypeScript that looks like this: const baseElements: IBaseElement[] An IBaseElement contains some information: export interface IBaseElement{ a: number; b: string; } There are two classes that implement the IBaseElement interface: ...

Are you searching for ways to convert an object into an array?

I have a dynamically built object and I need to extract specific fields (the dynamic ones) from it and convert them into an array. In the following code snippet, my goal is to convert towers[X] into an array of objects. {id: "", description: "Teste", tow ...

Passing a class object from a child component to a parent component in Angular 4

Passing a class object like Person from parent component to a child component is no issue. However, I would also like to manipulate this object in the child component and send it back to the parent component. The child component class looks like this: ex ...

Error: Unable to assign generic type due to type mismatch

I'm struggling to understand the type error generated by the following code. Can anyone point out what I might be doing incorrectly? Type '(state: State) => State' is not assignable to type 'Action'. Types of parameters &apos ...