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文件夹,复制后放在这个文件夹

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

要将Vue项目改为使用prerender-spa-plugin,需要进行以下步骤: 1. 安装prerender-spa-plugin插件: ``` npm install prerender-spa-plugin --save-dev ``` 2. 在webpack配置文件中引入插件: ``` const PrerenderSPAPlugin = require('prerender-spa-plugin'); ``` 3. 在plugins数组中添加插件配置: ``` plugins: [ new PrerenderSPAPlugin({ staticDir: path.join(__dirname, 'dist'), routes: ['/', '/about', '/contact'], // 可选项,生成的文件存储的路径,默认为 `./prerendered` outputDir: path.join(__dirname, 'prerendered'), // 可选项,生成文件的后缀名,默认为 `.html` postProcess (renderedRoute) { // 对渲染后的路由文件进行额外处理 } }) ] ``` 4. 在`package.json`文件中添加一个脚本: ``` "scripts": { "prerender": "npm run build && node prerender.js" } ``` 5. 创建一个名为`prerender.js`的文件,并添加以下代码: ``` const path = require('path'); const PrerenderSPAPlugin = require('prerender-spa-plugin'); const rendererPath = path.join(__dirname, 'dist', 'server', 'bundle.js'); const renderer = require(rendererPath); const options = { staticDir: path.join(__dirname, 'dist'), routes: ['/'], renderer: new PrerenderSPAPlugin.PuppeteerRenderer({ renderAfterDocumentEvent: 'render-event', headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], }), }; const prerenderer = new PrerenderSPAPlugin(options); prerenderer .initialize() .then(() => { return prerenderer.renderRoutes(['/']); }) .then((renderedRoutes) => { console.log('Prerendering successful!'); console.log(renderedRoutes); }) .catch((error) => { console.error('Prerendering failed:'); console.error(error); }); ``` 6. 运行`npm run prerender`命令,生成预渲染文件。 以上就是将Vue项目改为使用prerender-spa-plugin的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值