我大约两个月前遇到了和你一样的问题。我对React的服务器端渲染知识非常少,对其概念感到困惑。然而,我不想使用create-react-app cli,我想使用自己的脚手架。在做研究时,我发现我必须配置我的webpack来处理404重载回退。
这是我的当前webpack设置:
请注意,只需关注允许您在使用v4时刷新页面而不会抛出404错误的“historyApiFallback: true”。此外,我忘记提到这需要webpack-dev-server才能正常工作。
const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const HtmlWebPackPlugin = require('html-webpack-plugin');
var browserConfig = {
devServer: {
historyApiFallback: true,
proxy: {
"/api": "http://localhost:3012"
}
},
entry: ['babel-polyfill', __dirname + '/src/index.js'],
output: {
path: path.resolve(__dirname + '/public'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['react', 'env', 'stage-0']
}
}
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './public/index.html',
})
]
}
var serverConfig = {
target: 'node',
externals: [nodeExternals()],
entry: __dirname + '/server/main.js',
output: {
path: path.resolve(__dirname + '/public'),
filename: 'server.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
query: {
presets: ['react', 'env', 'stage-0']
}
}
}
]
}
}
module.exports = [browserConfig, serverConfig]
create-react-app cli
,它会自动为您完成此操作。但是,如果您使用自己的样板文件,则需要使用 webpack 来处理 404 回退。 - Curious13publicPath: '/'
。 - Dennis