預(yù)渲染模式
預(yù)渲染 prerender-spa-plugin 配置生成多頁面,解決首屏白屏問題,提升用戶體驗。同時配合 vue-meta-info 可以生成 title 和 meta標(biāo)簽,可解決SPA頁面的SEO痛點。
-
prerender-spa-plugin 使用方法
- 安裝 prerender-spa-plugin
npm i prerender-spa-plugin --save - 使用
我的項目是用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ù)渲染的路由路徑 我這里做的是首頁 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'))}}),兩者的事件名稱要對應(yīng)上。 // renderAfterDocumentEvent: 'render-event' }) }) ) } };- 重新打包后訪問項目就能看到效果
- 安裝 prerender-spa-plugin
注意:官方文檔上 路由模式必須為 history 。如果不設(shè)置history模式,也能運行和生成文件,每個index.html文件的內(nèi)容都會是一樣的。所以必須使用 history模式