常見的<font color=red>Vue單頁SPA</font>構建以後的index.html只是一個包含根節點的空白頁面,當全部須要的js加載完畢以後,纔會開始解析並建立<font color=red>vnode</font>,而後再渲染出真實的DOM。當這些js文件過大而網速又很慢或者出現意料以外的報錯時,就會出現所謂的白屏。html
並且單頁SPA還有一個很大的弊端就是對SEO很不友好。那麼如何解決這些問題呢?vue
<font color=red>SSR(Nuxt)--</font>固然是很好的解決方案,但這也意味着必定的學習成本和運維成本,而若是你已經有了一個現成的<font color=red>Vue單頁應用</font>,轉向<font color=red>SSR</font>也並非一個無縫的過程,須要投入更大的學習成本去開發。node
那麼<font color=red>預渲染</font>就顯得更加合適了。只須要安裝一個<font color=red>Webpack</font>的插件+一些簡單的<font color=red>Webpack</font>配置就能夠解決上述的兩個問題。webpack
<font color=orange>用手機預覽效果更佳(PC端請用手機調試模式)</font>nginx
預覽地址:http:fancy.czero.cngit
Github:https://github.com/czero1995/fancy-storegithub
打包完成的項目結構:web
預覽地址:http:router.czero.cnnpm
Github:https://github.com/czero1995/fancy-store/tree/prerender服務器
打包完成的項目結構:
查看源碼:<font color=red>通過prerender預渲染事後的代碼</font>:
1.須要將<font color=red>router</font>設爲<font color=red>history</font>模式。
2.修改服務器<font color=red>nginx</font>的配置(刷新頁面的時候會作重定向跳轉)
try_files $uri /index.html;
<font color=orange>提個醒:</font>以下圖,這裏有個大坑,當須要用懶加載來作預渲染,nginx上配置
<font color=red> try_files $uri $uri/ /index.html;</font>
沒在首頁刷新頁面的時候,會報錯。
3.安裝<font color=red>prerender-spa-plugin</font>
cnpm install prerender-spa-plugin --save
4.修改<font color=red>build/webpack.prod.conf.js</font>下的配置爲:
5.將<font color=red>config/index.js</font>裏的<font color=red>build</font>中的<font color=red>assetsPublicPath</font>字段設置爲<font color=red>'/'</font>
6.調整<font color=red>main.js</font>
new Vue({ i18n, router, store, render: h => h(App) }).$mount('#app', true)
7.執行<font color=red>npm run build</font>你會發現,最後打包出來的目錄和以前不太同樣,都是一些渲染完成好的頁面
npm install vue-meta-info --save
import Vue from 'vue' import MetaInfo from 'vue-meta-info' Vue.use(MetaInfo)
export default { metaInfo: { title: 'My Example App', // set a title meta: [{ // set meta name: 'keyWords', content: 'My Example App' }] link: [{ // set link rel: 'asstes', href: 'https://assets-cdn.github.com/' }] } }
無預渲染:https://github.com/czero1995/fancy-store
有預渲染:https://github.com/czero1995/fancy-store/tree/prerender