Vue-CLI路由懒加载预渲染项目实战

常见的<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>:

将Vue-cli单页SPA转为预渲染

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>你会发现,最后打包出来的目录和以前不太同样,都是一些渲染完成好的页面

加持vue-meta-info提升SEO

npm install vue-meta-info --save

全局引入 vue-meta-info

import Vue from 'vue'
import MetaInfo from 'vue-meta-info'

Vue.use(MetaInfo)

组件内静态使用 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/'
      }]
    }
  }

Github

无预渲染:https://github.com/czero1995/fancy-store

有预渲染:https://github.com/czero1995/fancy-store/tree/prerender

相关文章
相关标签/搜索