路由在webpack + react项目中不起作用



我正在用webpack + React + React -router + typescript构建一个应用程序,我被路由卡住了,我有两个路由,默认的'/'和'/test',无论我做什么,默认的都是到达。我做了很多研究,发现很多人都有同样的问题,但他们给出的解决方案并不适用于我。

我试着:

  • 在webpack中添加historyApiFallback: true。配置(https://www.robinwieruch.de/webpack-react-router)。
  • 添加公共路径:output:{…publicPath: '/',}
  • 如何允许webpack-dev-server允许来自react-router的入口点

我猜是因为我对wepack缺乏了解,我错过了一些东西,有人能帮我吗?

下面是我的代码:

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')
);

对于仍然有此问题的人,请确保将此添加到您的webpack配置中。

output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true
}

我发现问题不在于webpack,而在于主路由中缺少'exact'属性,否则所有其他路由都将与主路由匹配。

<Route exact path='/'>

相关内容

  • 没有找到相关文章

最新更新