Sample repo demonstrating the issue is here.
我试图设置webpack dev服务器,以便:
/
的请求由public/landing.html
(静态目标网页)使用create-react-app
和based on webpack-dev-server
's options,我已按照以下方式设置webpackDevServer.config.js
:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
rewrites: [
// shows views/landing.html as the landing page
{ from: /^\/$/, to: 'landing.html' },
// shows views/subpage.html for all routes starting with /subpage
{ from: /^\/subpage/, to: 'subpage.html' },
// shows views/404.html on all other pages
{ from: /./, to: '404.html' },
],
},
当我在这里开始使用webpack时,我看到的是:
/subpage
的请求已正确路由至subpage.html
/foo
的请求被正确路由到404.html
。最终,这些将由我的React应用程序处理。/
的请求被错误地路由到我的React应用程序。如何让landing.html
回复/
的请求?
答案 0 :(得分:3)
我以/customers?page=5
结束opening a bug request并发现这不是错误,而是配置失败。
具体而言,问题是在webpack-dev-middleware
旁边使用HtmlWebpackPlugin
。我相信在正则表达式匹配之前处理插件,historyApiFallback
的默认文件输出为HtmlWebpackPlugin
;这意味着开箱即用,index.html
将始终路由到/
输出文件。
解决方法是在HtmlWebpackPlugin
中设置自定义文件名,这样您就可以再次控制匹配。 Here's a sample repo demonstrating the fix这里是webpack配置:
HtmlWebpackPlugin
答案 1 :(得分:1)
想到两个想法:
npm run build
后,部署的应用程序将不遵循Webpack Dev Server中配置的相同规则即使我错误地认为#1,如果您计划部署应用程序,#2似乎也是一个更大的问题。这导致我建议一个替代设置,它将适用于dev 和生产(或部署的任何地方)。
一些选择:
/
和/subpage
)和通配符(其他所有内容)/
和/subpage
)和通配符(其他所有内容)在尝试设置路线时,我能够实现此设置:
landing.html
时显示/
subpage.html
时显示/subpage
app.html
为此,请进行以下更改:
将/public/index.html
移至/public/app.html
mv ./public/index.html ./public/app.html
在/config/webpackDevServer.config.js
中,将historyApiFallback
更新为:
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
rewrites: [
// shows views/landing.html as the landing page
{ from: /^\/$/, to: "landing.html" },
// shows views/subpage.html for all routes starting with /subpage
{ from: /^\/subpage/, to: "subpage.html" },
// shows views/app.html on all other pages
// but doesn't work for routes other than app.html
{ from: /./, to: "app.html" }
]
}
在/config/paths.js
更新appHTML
至:
appHtml: resolveApp("public/app.html")
在/config/webpack.config.dev.js, update
插件中包含:
new HtmlWebpackPlugin({
filename: "app.html",
inject: true,
template: paths.appHtml
})
请求随机网址(例如localhost:3000/foo
)将返回空白页面,但包含app.html
页面中的HTML,而不会注入捆绑的<script>
标记。所以也许你可以找到解决这个最后障碍的方法。