SEO优化 prerender-spa-plugin工具使用 踩坑记录

  1. 安装prerender-spa-plugin
yarn add prerender-spa-plugin
或
npm install prerender-spa-plugin

初始配置 后面记录踩的坑

  1. 配置路由

const routes = [
  {
    path: '/',
    redirect: {
      path: '/HomeView'
    },
  },
  {
    path: '/home',
    redirect: {
      path: '/HomeView'
    },
  },
  { 
    path: '/HomeView',
    component: HomeView
  },
  {
    path: '/CompanyProfile',
    component: CompanyProfile
  },
  {
    path: '/ConsultationChannel',
    component: ConsultationChannel
  },
  {
    path: '/IndustryIntroduction',
    name: 'IndustryIntroduction',
    component: IndustryIntroduction,
  },
  {
    path: '/ProductIntroduction',
    name: 'ProductIntroduction',
    component: ProductIntroduction,
  },
  {
    path: '/ProductsServices',
    name: 'ProductsServices',
    component: ProductsServices,
  },
  {
    path: '/CompanyCulture',
    name: 'CompanyCulture',
    component: CompanyCulture,
  },
  {
    
    path: '/CompanyAbout',
    name: 'CompanyAbout',
    component: CompanyAbout,
  },
  {
    path: '/CompanyIntroduction',
    name: 'CompanyIntroduction',
    component: CompanyIntroduction,
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})
  1. vue.config.js配置
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;

module.exports = {
  // 服务器环境production  本地环境development 
  // "../"  其他配置无法打包
  publicPath: process.env.NODE_ENV === "production" ? "../" : "./",
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: 'home',
  configureWebpack: config => {
    if (process.env.NODE_ENV !== 'production') return;
    return {
      plugins: [
        new PrerenderSPAPlugin({
          // 生成文件的路径,这里使用了相对路径
          staticDir: path.join(__dirname, 'home'),
          // 需要进行预渲染的路由,这里需要根据你的实际路由配置来设置
          routes: [ '/', '/HomeView', '/CompanyProfile', '/ConsultationChannel', '/IndustryIntroduction', '/ProductIntroduction', '/ProductsServices', '/CompanyCulture', '/CompanyAbout', '/CompanyIntroduction'],
          // 渲染器配置,这里使用 Puppeteer 渲染
          renderer: new Renderer({
            inject: {
              foo: 'bar'
            },
            // 在渲染之前等待一定时间,以确保 SPA 中的异步操作完成
            renderAfterTime: 5000,
            headless: false,
            // 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
            renderAfterDocumentEvent: 'render-event'
          })
        })
      ]
    }
  }
}

遇到的问题

  1. publicPath配置为…/后, 在服务器静态资源和路由加载找不到子路径的目录,publicPath改为真实的子路径后无法build 不加publicPath静态文件访问存在问题

解决

此问题解决出处
解决方法

  publicPath: process.env.NODE_ENV === "production" ? '/home/' : "./",,
  outputDir: path.join(__dirname, "./home", "/home/"),
    configureWebpack: config => {
    if (process.env.NODE_ENV !== 'production') return;
    return {
      plugins: [
        new PrerenderSPAPlugin({
          // 生成文件的路径,这里使用了相对路径
          staticDir: path.join(__dirname, 'home/'),
          indexPath: path.join(__dirname, "home/home/index.html"), //重要
          // 需要进行预渲染的路由,这里需要根据你的实际路由配置来设置
          routes: [ '/', '/HomeView', '/CompanyProfile', '/ConsultationChannel', '/IndustryIntroduction', '/ProductIntroduction', '/ProductsServices', '/CompanyCulture', '/CompanyAbout', '/CompanyIntroduction'],
          // 渲染器配置,这里使用 Puppeteer 渲染
          renderer: new Renderer({
            inject: {
              foo: 'bar'
            },
            // 在渲染之前等待一定时间,以确保 SPA 中的异步操作完成
            renderAfterTime: 5000,
            headless: false,
            // 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
            renderAfterDocumentEvent: 'render-event'
          })
        })
      ]
    }
  }
  1. 升级到服务器后,在使用 prerender-spa-plugin 进行预渲染处理时,如果手动刷新 Vue 路由后路径末尾会出现 /,通常这是由于浏览器的默认行为导致的,特别是在使用 history 模式的 Vue 路由时比较常见。这种行为可能会影响到预期的路由匹配和渲染

解决

  • Vue Router 中设置 strict: true,这样在路由跳转时会自动去掉末尾的斜杠,避免不必要的重定向。
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})
  • 在路由的 beforeEnter 钩子中,可以检查并处理路径末尾的斜杠,确保它符合预期的路由结构。
  • 如果在路由中传参,直接访问带参数的路由,用下面的方法解决了斜杠问题,可能参数也会被干掉后丢失,(http:ip:port/HomeView?id=123 -> http:ip:port/HomeView), 所以需要在加上一句 query: to.query
const routes = [
  {
    path: '/',
    redirect: {
      path: '/HomeView'
    },
  },
  { 
    path: '/HomeView',
    component: HomeView,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
      	// 加上query: to.query 可以避免参数被前面的slice干掉后丢失
        next({ path: to.path.slice(0, -1), query: to.query });
      } else {
        next();
      }
    }
  },
  {
    path: '/CompanyProfile',
    component: CompanyProfile,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/ConsultationChannel',
    component: ConsultationChannel,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/IndustryIntroduction',
    name: 'IndustryIntroduction',
    component: IndustryIntroduction,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/ProductIntroduction',
    name: 'ProductIntroduction',
    component: ProductIntroduction,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/ProductsServices',
    name: 'ProductsServices',
    component: ProductsServices,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/CompanyCulture',
    name: 'CompanyCulture',
    component: CompanyCulture,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    
    path: '/CompanyAbout',
    name: 'CompanyAbout',
    component: CompanyAbout,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
  {
    path: '/CompanyIntroduction',
    name: 'CompanyIntroduction',
    component: CompanyIntroduction,
    beforeEnter: (to, from, next) => {
      if (to.path.endsWith('/')) {
        next({ path: to.path.slice(0, -1) });
      } else {
        next();
      }
    }
  },
 ]
  • 在以上问题处理完后,升级到服务器后,静态资源访问不到
资源访问不到
http://ip:port/home/static/css/app.e2f5f186.css

解决

打包生成home文件夹,在home文件夹下还有一个home文件夹,把这个里面的静态资源复制一份放在和它同级的目录下即可!

home/home下的文件夹,复制这些静态资源
home文件夹,复制后放在这个文件夹

自此目前遇到的所有问题都以解决

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值