vueSSR学习记录

vue预渲染: https://github.com/chrisvfritz/prerender-spa-plugin
官网里说的
在这里插入图片描述

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

module.exports = {
  plugins: [
    ...
    new PrerenderSPAPlugin({
      // Required - The path to the webpack-outputted app to prerender.
      staticDir: path.join(__dirname, 'dist'),

      // Optional - The path your rendered app should be output to.
      // (Defaults to staticDir.)
      outputDir: path.join(__dirname, 'prerendered'),

      // Optional - The location of index.html
      indexPath: path.join(__dirname, 'dist', 'index.html'),

      // Required - Routes to render.
      routes: [ '/', '/about', '/some/deep/nested/route' ],

      // Optional - Allows you to customize the HTML and output path before
      // writing the rendered contents to a file.
      // renderedRoute can be modified and it or an equivelant should be returned.
      // renderedRoute format:
      // {
      //   route: String, // Where the output file will end up (relative to outputDir)
      //   originalRoute: String, // The route that was passed into the renderer, before redirects.
      //   html: String, // The rendered HTML for this route.
      //   outputPath: String // The path the rendered HTML will be written to.
      // }
      postProcess (renderedRoute) {
        // Ignore any redirects.
        renderedRoute.route = renderedRoute.originalRoute
        // Basic whitespace removal. (Don't use this in production.)
        renderedRoute.html = renderedRoute.html.split(/>[\s]+</gmi).join('><')
        // Remove /index.html from the output path if the dir name ends with a .html file extension.
        // For example: /dist/dir/special.html/index.html -> /dist/dir/special.html
        if (renderedRoute.route.endsWith('.html')) {
          renderedRoute.outputPath = path.join(__dirname, 'dist', renderedRoute.route)
        }

        return renderedRoute
      },

      // Optional - Uses html-minifier (https://github.com/kangax/html-minifier)
      // To minify the resulting HTML.
      // Option reference: https://github.com/kangax/html-minifier#options-quick-reference
      minify: {
        collapseBooleanAttributes: true,
        collapseWhitespace: true,
        decodeEntities: true,
        keepClosingSlash: true,
        sortAttributes: true
      },

      // Server configuration options.
      server: {
        // Normally a free port is autodetected, but feel free to set this if needed.
        port: 8001
      },
//这个配置很重要 如果没有配置  就不会预编译
      // The actual renderer to use. (Feel free to write your own)
      // Available renderers: https://github.com/Tribex/prerenderer/tree/master/renderers
      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: {
          foo: 'bar'
        },

        // Optional - defaults to 0, no limit.
        // Routes are rendered asynchronously.
        // Use this to limit the number of routes rendered in parallel.
        maxConcurrentRoutes: 4,
//自己取名  很重要  在项目入口中使用 document.dispatchEvent(new Event('custom-render-trigger'))
        // Optional - Wait to render until the specified event is dispatched on the document.
        // eg, with `document.dispatchEvent(new Event('custom-render-trigger'))`
        renderAfterDocumentEvent: 'custom-render-trigger',

        // Optional - Wait to render until the specified element is detected using `document.querySelector`
        renderAfterElementExists: 'my-app-element',

        // Optional - Wait to render until a certain amount of time has passed.
        // NOT RECOMMENDED
        renderAfterTime: 5000, // Wait 5 seconds.

        // Other puppeteer options.
        // (See here: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions)
        headless: false // Display the browser window when rendering. Useful for debugging.
      })
    })
  ]
}

在main.js
在这里插入图片描述

prerender-spa-plugin
理解SSR https://ssr.vuejs.org/zh/

  1. 传统服务端渲染SSR
  2. 单页面应用SPA
  3. 服务端渲染SSR

1、传统web开发
传统web开发,网页内容在服务端渲染完成,一次性传输到浏览器。
在这里插入图片描述
2、单页应用 Single Page App
单页应用优秀的用户体验,使其逐渐成为主流,页面内容由JS渲染出来,这种方式成为客户端渲染。
在这里插入图片描述
spa缺点:

  • seo非常差
  • 首屏内容到达时间慢

概念
- 服务端渲染:将vue实例渲染为HTML字符串直接返回,在前端激活为交互程序

3、服务端渲染 Server Side Render

  • SSR解决方案,后端渲染出完整的首屏的dom结构返回,前端拿到的内容包括首屏及完整spa结构,应用激活后依然按照spa方式运行,这种页面渲染方式被称为服务端渲染(Server Side Render)

在这里插入图片描述

在这里插入图片描述
实践
新建工程
vue-cli创建工程(vuecli4)
node服务器用的是express

vue create ssr

安装依赖

 npm install vue vue-server-renderer express -S 

确保vue、vue-server-renderer、vue-template-compiler 版本一致

完整实现过程:

在这里插入图片描述在这里插入图片描述

在这里插入图片描述

数据预取

服务器端渲染的是应用程序的“快照”,如果应用依赖于一些异步数据,那么开始渲染之前,,需要先预取和解析好这些数据。

总结
服务端渲染的核心在于: 通过 vue-server-renderer插件的renderToString()方法,将vue实例转换为字符串插入到html文件

SSR优缺点都很明显

优点:

 - seo
 - 首屏显示时间

缺点:

 - 开发逻辑复杂
 - 开发条件限制:比如一些生命周期不能用(只有beforecreate、created可以用),一些第三方库会不能用
 - 服务器负载大

在这里插入图片描述

已经存在spa

  • 需要seo页面是否只有少数几个营销页面 可以考虑预渲染
  • 确实需要做ssr改造,利用服务器端爬虫技术 puppeteer (无头浏览器)
  • 在这里插入图片描述
  • 最后选择重构 全新项目建议使用nuxt.js
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值