[英]How to setup React Router with Webpack in ReactJs
webpack 新手,我嘗試配置 React Router Dom + webpack 但 Webpack bundle 不會在 react js 中加載 react router 組件,
問題:運行構建時,我在頁面中只看到<h1>React Router Example</h1>
標記結果,它沒有加載組件,請任何人幫助解決這個問題或分享任何鏈接
預期:當使用 Webpack 運行 react 應用程序時,我需要看到這個組件應該加載到頁面中<Route exact path="/" component={<Home/>} />
注意:僅組件不加載如果嘗試在沒有路由器的情況下加載單個組件它將加載
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
ReactDOM.render(<App />, document.getElementById('root'));
應用程序.js
import { Route, Routes, Link, BrowserRouter as Router } from 'react-router-dom';
import Home from './Home';
const App = () => {
return (
<Router>
<h1>React Router Example</h1>
<Routes>
<Route exact path="/" component={<Home/>} />
<Route path="/login" component={<h1>Login</h1>} />
</Routes>
</Router>
);
};
export default App;
webpack-config.js
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: 'babel-loader',
},
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
],
},
],
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
};
你可以使用開關
{/* A Switch looks through its children Routes and renders the first one that matches the current URL. */}
<Switch>
<Route path="/">
<Home />
</Route>
</Switch>
有關更多信息,請查看 URL - https://v5.reactrouter.com/web/guides/quick-start
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.