gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:30:32 25 4
gpt4 key购买 nike

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

我试过:

我想是因为我对 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,
},
};

应用程序.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>
);
}

索引.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
}

关于reactjs - 路由在 webpack + react 项目中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69436603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com