[英]/class/:id page doesn't show in React app
我正在開發 React 應用程序,在實現路由時遇到了一些問題。
<BrowserRouter>
<Layout>
<Route path="/" component={Home} exact={true} />
<Route path="/signin" component={Signin} />
<Route path="/register" component={Register} />
<Route path="/about" component={About} />
<Route path="/class/:id" component={Class} />
<Route path="/class" component={Classes} exact={true} />
</Layout>
</BrowserRouter>
當我在 local 上導航主頁時,即 localhost:8000 ,會顯示主頁。 當我單擊class
鏈接時,瀏覽器導航到/class
並顯示類頁面。 當我單擊特定類項時,瀏覽器導航到/class/:class-id
並顯示特定類詳細信息頁面。
但是當我在瀏覽器中手動輸入/class/:class-id
時,沒有顯示類詳細信息頁面。 當我檢查瀏覽器時, bundle.js
被稱為localhost:8000/class/bundle.js
。 但是bundle.js
被稱為localhost:8000/bundle.js
。
我正在使用 webpack,這是 webpack 配置。
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const path = require('path');
module.exports = {
mode: 'development',
entry: "./src/index.js",
// Here the application starts executing
// and webpack starts bundling
output: {
// options related to how webpack emits results
path: path.resolve(__dirname, "dist"), // string
// the target directory for all output files
// must be an absolute path (use the Node.js path module)
filename: "bundle.js", // string,
// the filename template for entry chunks,
assetModuleFilename: "assets/[hash][ext][query]"
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader'
},
{
test: /\.less$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "less-loader" }
]
},
{
test: /\.(jpe?g|png|gif|svg)$/,
type: "asset/resource"
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
'@': path.resolve(__dirname, 'src/'),
}
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.ico',
}),
new InterpolateHtmlPlugin({
PUBLIC_URL: 'http://localhost:8000/public'
})
],
devServer: {
historyApiFallback: true,
port: 8000,
open: true
},
externals: {
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:4000'
})
}
}
我找到了一個簡單的解決方案。
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
favicon: './public/favicon.ico',
publicPath: '/'
}),
new InterpolateHtmlPlugin({
PUBLIC_URL: 'http://localhost:8000/public'
})
]
我將publicPath: '/'
添加到 HtmlWebpackPlugin 以便bundle.js
絕對路徑,而不是相對路徑。 localhost:8000/bundle.js
所以現在可以完美運行了。
另一方面,我研究了同構應用程序,但發現它的主要好處是提高性能和 SEO 實施。
在具有客戶端渲染能力的現代 JS 框架之后,這個想法似乎可以提高性能和 SEO 實施。 自從 Google 宣布並支持關於 javascript 的 SEO 后,這個想法失去了狂熱,但仍然被用於它的好處。
我確信同構和包羅萬象的方法可以完美地解決我的問題。 但就目前而言,我更喜歡我目前的解決方案,它很簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.