預(yù)渲染模式
預(yù)渲染 prerender-spa-plugin 配置生成多頁(yè)面簇秒,解決首屏白屏問(wèn)題糊秆,提升用戶(hù)體驗(yàn)耘擂。同時(shí)配合 vue-meta-info 可以生成 title 和 meta標(biāo)簽蓖租,可解決SPA頁(yè)面的SEO痛點(diǎn)勋锤。
-
prerender-spa-plugin 使用方法
- 安裝 prerender-spa-plugin
npm i prerender-spa-plugin --save
- 使用
我的項(xiàng)目是用vue-cli3
進(jìn)行的搭建饭玲,在 vue.config.js 文件里進(jìn)行如下操作。
const PrerenderSPAPlugin = require('prerender-spa-plugin'); const Renderer = PrerenderSPAPlugin.PuppeteerRenderer; const path = require('path'); module.exports = { configureWebpack: config => { config.plugins.push( new PrerenderSPAPlugin({ staticDir: path.join(__dirname, 'dist'), // 需要進(jìn)行預(yù)渲染的路由路徑 我這里做的是首頁(yè) routes: ['/'], // html文件壓縮 minify: { minifyCSS: true, // css壓縮 removeComments: true // 移除注釋 }, renderer: new Renderer({ // Optional - The name of the property to add to the window object with the contents of `inject`. injectProperty: '__PRERENDER_INJECTED', // Optional - Any values you'd like your app to have access to via `window.injectProperty`. inject: {}, // 在 main.js 中 new Vue({ mounted () {document.dispatchEvent(new Event('render-event'))}})叁执,兩者的事件名稱(chēng)要對(duì)應(yīng)上茄厘。 // renderAfterDocumentEvent: 'render-event' }) }) ) } };
- 重新打包后訪問(wèn)項(xiàng)目就能看到效果
- 安裝 prerender-spa-plugin
注意:官方文檔上 路由模式必須為 history
。如果不設(shè)置history模式谈宛,也能運(yùn)行和生成文件次哈,每個(gè)index.html文件的內(nèi)容都會(huì)是一樣的。所以必須使用 history
模式