Reputation: 31
I'm building an app with webpack + React + react-router + typescript and I got stuck with the routing, I have two routes, the default '/' and '/test', no matter what I do only the default is reach. I did a lot of research and find many people with the same problem, but all the solutions they gave did not work for me.
I tried:
I guess because of my lack of knowledge with wepack I'm missing something, can someone help?
Here's my code:
Webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.join(__dirname, 'src', 'index.tsx'),
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript',
],
},
},
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: {
loader: 'file-loader',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
}),
],
devServer: {
port: '3000',
historyApiFallback: true,
},
};
App.tsx:
import React, { useState } from 'react';
import { IntlProvider } from 'react-intl';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Dashboard from './pages/dashboard';
import SurveyList from './pages/survey/list';
import messages from './intl/messages';
import { getStoredLanguage } from './intl/languageStorage';
function App() {
const [appLang, setAppLang] = useState(getStoredLanguage());
return (
<IntlProvider
locale={appLang}
messages={appLang === 'en' ? messages.en : messages.pt}
>
<Router>
<Link to='/'>Dashboard</Link>
<br />
<Link to='/test'>Surveys</Link>
<Switch>
<Route path='/'>
<Dashboard />
</Route>
<Route path='/test'>
<SurveyList />
</Route>
</Switch>
</Router>
</IntlProvider>
);
}
index.tsx:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Upvotes: 3
Views: 7021
Reputation: 195
For anybody still having this issue, make sure to add this to your webpack config.
output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true
}
Upvotes: 18
Reputation: 31
I figure out that the problem was not the webpack, but the lack of the attribute 'exact' in the main route otherwise all other routes are going to match with the main.
<Route exact path='/'>
Upvotes: 0