问题是,如果将"/"添加到要预渲染的路由中,然后在不是"/"的页面上刷新,则会导致浏览器使用预呈现的索引文件内容。
如何配置 Vue 和 PSPA,以便根目录是预渲染的,但 Vue 知道使用原始(空(index.html 文件来渲染非预渲染路由?
我尝试在/public 中添加一个 index.template 文件,然后将其添加到 PSA 配置中:
indexPath: path.join(__dirname, 'dist', 'index.template.html'),
但这未能建立。这是正确的方法吗?
我将提供一个通用的解决方案。此解决方案还可以使用prerender-spa插件帮助在加载时遇到"白闪"的人,记录在此处:https://github.com/chrisvfritz/prerender-spa-plugin/issues/193
解决此问题的步骤如下:
- 告诉 Pre-SPA 插件不要使用 index.html 作为其模板文件。
indexPath: path.join(__dirname, 'dist', 'app.html')
- 告诉 Vue (CLI 3( 将此文件提供给 Pre-SPA:
chainWebpack: config => {
if (process.env.NODE_ENV !== 'production') return
config
.plugin('html')
.tap(args => {
args[0].template = path.join(__dirname, 'public', 'index.html');
args[0].filename = 'app.html';
return args
})
}
- 将 Web 服务器配置为对根 ("/"( 使用与所有其他路径不同的入口点。由于我使用的是 firebase,因此我已将其添加到 firebase.json 中:
"rewrites": [
{
"source": "**",
"destination": "/app.html"
},
{
"source": "/",
"destination": "/index.html"
}
]
构建后,您的/dist 文件夹将有一个 app.html 文件和一个索引.html文件。
每当有人刷新您网站上尚未预先呈现的页面时,都会使用该 app.html 文件。app.html 文件应该是"干净的",并且不包含预呈现的信息。
index.html 文件仅在根登陆时使用,并且包含所有预呈现的内容。
根据 https://github.com/SolarLiner/vue-cli-plugin-prerender-spa#backend-routing-configuration-for-deployments 中的文档,您只需将预呈现的路由指向服务器配置中的index.html
和非预呈现的路由指向app.html
。