vue 使用prerender-spa-plugin预渲染插件时,加载https渲染页面和修复 ...options.navigationOptions bug

8 篇文章 0 订阅

vue 使用prerender-spa-plugin预渲染插件时,加载https渲染页面和修复 ...options.navigationOptions bug

修改文件 node_modules/@prerenderer/renderer-puppeteer/es6/renderer.js

***************************************************** 标注的是修改过的地方

const promiseLimit = require('promise-limit')
const puppeteer = require('puppeteer')

const waitForRender = function (options) {
  options = options || {}

  return new Promise((resolve, reject) => {
    // Render when an event fires on the document.
    if (options.renderAfterDocumentEvent) {
      if (window['__PRERENDER_STATUS'] && window['__PRERENDER_STATUS'].__DOCUMENT_EVENT_RESOLVED) resolve()
      document.addEventListener(options.renderAfterDocumentEvent, () => resolve())

    // Render after a certain number of milliseconds.
    } else if (options.renderAfterTime) {
      setTimeout(() => resolve(), options.renderAfterTime)

    // Default: Render immediately after page content loads.
    } else {
      resolve()
    }
  })
}

class PuppeteerRenderer {
  constructor (rendererOptions) {
    this._puppeteer = null
    this._rendererOptions = rendererOptions || {}

    if (this._rendererOptions.maxConcurrentRoutes == null) this._rendererOptions.maxConcurrentRoutes = 0

    if (this._rendererOptions.inject && !this._rendererOptions.injectProperty) {
      this._rendererOptions.injectProperty = '__PRERENDER_INJECTED'
    }
  }

  async initialize () {
    try {
      // Workaround for Linux SUID Sandbox issues.
      if (process.platform === 'linux') {
        if (!this._rendererOptions.args) this._rendererOptions.args = []

        if (this._rendererOptions.args.indexOf('--no-sandbox') === -1) {
          this._rendererOptions.args.push('--no-sandbox')
          this._rendererOptions.args.push('--disable-setuid-sandbox')
        }
      }

      this._puppeteer = await puppeteer.launch(this._rendererOptions)
    } catch (e) {
      console.error(e)
      console.error('[Prerenderer - PuppeteerRenderer] Unable to start Puppeteer')
      // Re-throw the error so it can be handled further up the chain. Good idea or not?
      throw e
    }

    return this._puppeteer
  }

  async handleRequestInterception (page, baseURL) {
    await page.setRequestInterception(true)

    page.on('request', req => {
      // Skip third party requests if needed.
      if (this._rendererOptions.skipThirdPartyRequests) {
        if (!req.url().startsWith(baseURL)) {
          req.abort()
          return
        }
      }

      req.continue()
    })
  }

  async renderRoutes (routes, Prerenderer) {
    const rootOptions = Prerenderer.getOptions()
    const options = this._rendererOptions

    const limiter = promiseLimit(this._rendererOptions.maxConcurrentRoutes)

    const pagePromises = Promise.all(
      routes.map(
        (route, index) => limiter(
          async () => {
            const page = await this._puppeteer.newPage()

            if (options.consoleHandler) {
              page.on('console', message => options.consoleHandler(route, message))
            }

            if (options.inject) {
              await page.evaluateOnNewDocument(`(function () { window['${options.injectProperty}'] = ${JSON.stringify(options.inject)}; })();`)
            }


            //这里修改了
            //*****************************************************
            const baseURL = `https://dev.baidu.com`  //这样可以修改https渲染页面
            // const baseURL = `http://localhost:${rootOptions.server.port}`

            // Allow setting viewport widths and such.
            if (options.viewport) await page.setViewport(options.viewport)

            await this.handleRequestInterception(page, baseURL)

            // Hack just in-case the document event fires before our main listener is added.
            if (options.renderAfterDocumentEvent) {
              page.evaluateOnNewDocument(function (options) {
                window['__PRERENDER_STATUS'] = {}
                document.addEventListener(options.renderAfterDocumentEvent, () => {
                  window['__PRERENDER_STATUS'].__DOCUMENT_EVENT_RESOLVED = true
                })
              }, this._rendererOptions)
            }
            

            //这里修改了 ,解决 ... 语法不支持的bug
            //*****************************************************
            const navigationOptions = { waituntil: 'networkidle0' };
            if(options.navigationOptions){
                for(var xx in options.navigationOptions){
                    navigationOptions[xx] = options.navigationOptions[xx]
                }
            }
            // const navigationOptions = (options.navigationOptions) ? { waituntil: 'networkidle0', ...options.navigationOptions } : { waituntil: 'networkidle0' };
            await page.goto(`${baseURL}${route}`, navigationOptions);

            // Wait for some specific element exists
            const { renderAfterElementExists } = this._rendererOptions
            if (renderAfterElementExists && typeof renderAfterElementExists === 'string') {
              await page.waitForSelector(renderAfterElementExists)
            }
            // Once this completes, it's safe to capture the page contents.
            await page.evaluate(waitForRender, this._rendererOptions)

            const result = {
              originalRoute: route,
              route: await page.evaluate('window.location.pathname'),
              html: await page.content()
            }

            await page.close()
            return result
          }
        )
      )
    )

    return pagePromises
  }

  destroy () {
    this._puppeteer.close()
  }
}

module.exports = PuppeteerRenderer

 

Vue渲染是指在构建Vue应用程序,将页面提前渲染成静态HTML文件,以便在服务器端优化SEO和提升加载速度。引用中介绍了一种使用vue-cli-plugin-prerender-spa的方法来实现这个功能。 要使用vue-cli-plugin-prerender-spa,您可以按照以下步骤操作: 1. 首先,确保您的Vue应用程序使用vue-cli。如果没有,请先安装vue-cli,并创建一个新的Vue项目。 2. 安装vue-cli-plugin-prerender-spa插件,可以通过运行以下命令来完成: ``` vue add prerender-spa ``` 3. 安装完成后,您可以在Vue项目的根目录下找到一个新的文件夹,名为prerender,其中包含了渲染的配置文件prerender.config.js。您可以在这个文件中配置需要渲染的路由和其他相关设置。 4. 根据您的需求,编辑prerender.config.js文件,指定需要渲染的路由,并进行其他必要的配置。 5. 运行以下命令来构建渲染的静态HTML文件: ``` npm run build ``` 6. 构建完成后,您将在dist文件夹中找到渲染的静态HTML文件,可以将这些文件部署到服务器上,或者使用它们来进行SEO优化。 引用中的内容可以给您提供更详细的vue-cli-plugin-prerender-spa使用说明和配置示例。希望这些信息能对您有所帮助。 : https://github.com/chrisvfritz/prerender-spa-plugin : https://www.npmjs.com/package/vue-cli-plugin-prerender-spa : https://github.com/ml4a/ml4a-guides/blob/master/notebooks/simple_image_classification_with_pytorch.md<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue-cli单页面渲染seo-prerender-spa-plugin操作](https://download.csdn.net/download/weixin_38627234/12924216)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [vue-cli-plugin-prerender-spa:通过渲染Vue应用程序来增强SEO。 由prerender-spa-plugin提供支持](https://download.csdn.net/download/weixin_42134094/18687118)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [毕设项目:基于SpringBoot+Vue前后端分离 实现的宿舍管理系统](https://download.csdn.net/download/qq_35831906/88227375)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值