N
N
n1ksON2021-06-16 12:09:41
React
n1ksON, 2021-06-16 12:09:41

How to use react-router-dom with webpack?

I set up webpack and everything worked until I installed react-router-dom and started using Route.
webpack.config.js:

const webpack = require('webpack');
const path = require('path');

const config = {
  entry: [
    'react-hot-loader/patch',
    './src/index.js'
  ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.png$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              mimetype: 'image/png'
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [
      '.js',
      '.jsx'
    ],
    alias: {
      'react-dom': '@hot-loader/react-dom'
    }
  },
  devServer: {
    contentBase: './dist',
    historyApiFallback: true
  }
};

module.exports = config;

index.js:
import React from 'react';
import { render } from 'react-dom';
import App from "./components/App";
import store from './store';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import "./index.css";

render(
  <React.StrictMode>
    <BrowserRouter>
      <Provider store={store}>
        <App />
      </Provider>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

app.js:
import React from "react";
import { hot } from 'react-hot-loader/root';
import { Switch, Route } from "react-router-dom";
import Home from '../pages/Home'
import Test from '../pages/Test'

const App = () => {
  return (
    <div className="app">
        <Switch>
          <Route path="/test" component={Test} />
          <Route path="*" component={Home} />
        </Switch>
    </div>
  );
}

export default hot(App);


If you change the url by using Link, then everything is displayed and changed correctly.
If you change the url yourself through the address bar or reload the page, then an error is generated: Cannot GET /test
In the console: GET http://localhost:8080/test 404 (Not Found)

When I used create-react-app, there were no problems with react-router-dom. So the question is: How to use react-router-dom along with webpack so that everything works correctly and the pages load as expected?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TRNER, 2021-06-16
@n1ksON

devServer: {
    contentBase: './dist',
    historyApiFallback: true,
}

I
Igor Makhov, 2021-06-16
@Igorgro

Most likely the problem is the same as here, check: How to connect Express Router with React Router?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question