【Vue】预渲染之prerender-spa-plugin解析,方便搜索引擎的抓取

项目背景:对于那些需要推广,希望能在百度搜索时排名靠前的网站而言,使用单页面应用的无法被抓取

背景,VUE项目想SEO优化,但vue是单页面应用,不利于搜索引擎的抓取

实现过程,采用预渲染

主要使用 prerender-spa-plugin 插件,其与SSR一样都可以加快页面的加载速度,

优缺点
  • 简单易上手
  • 对原有项目改动小
  • 不太适合变动较频繁的页面

SPA单页面应用简介

  • 使用MVVM经典模式,后端数据和页面结构分离
  • 架构清晰,前端交互逻辑,后端负责数据处理;用户体验好,加载页面速度快
  • 页面内容的改变不需要加载整个页面,避免了非必要的页面条状和重新渲染,也就是局部刷新
    在这里插入图片描述

步骤一,导入预渲染插件

npm i prerender-spa-plugin -D

步骤二,vue.config.js中增加配置

const {
    
     defineConfig } = require('@vue/cli-service')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const path = require('path')
module.exports = defineConfig({
    
    
  transpileDependencies: true,
  productionSourceMap: true,
  configureWebpack: (config) => {
    
    
    if (process.env.NODE_ENV === 'production') {
    
    
      config.plugins.push(
        new PrerenderSPAPlugin({
    
    
          staticDir: path.join(__dirname, 'dist'),
          routes: ['/'],
        })
      )
    }
  },
})

步骤三,npm run build

结果必定有报错!但不慌,改!
  • 原因是:这个包有问题
    在这里插入图片描述
解决方法:使用已经被修改的库
npm i @dreysolano/prerender-spa-plugin
替换一下旧包的引入,替换完已可以正常打包,但还有个小警告,解决他!
const PrerenderSPAPlugin = require('@dreysolano/prerender-spa-plugin')
错误2 小警告

在这里插入图片描述

解决方法
  • 在babel.config.js中
module.exports = {
    
    
  compact: false,
  presets: [
    '@vue/cli-plugin-babel/preset'
  ]
}
错误三,如果你发现你的代码在打包过程中,一直循环中,
解决方法,在main.js中添加代码
new Vue({
    
    
  router,
  store,
  render: h => h(App),  // 预渲染
  mounted() {
    
    
    document.dispatchEvent(new Event('render-event'))
  }
}).$mount('#app')

猜你喜欢

转载自blog.csdn.net/weixin_44899940/article/details/130707605