Vue的seo优化

本文介绍了在Vue2项目中进行SEO优化的方法,包括使用vue-meta-info和prerender-spa-plugin,并针对打包后样式和JS丢失的问题提供了解决方案,即在main.js中的特定跳转链接在打包时做临时替换,待打包完成后再恢复。

更新于:2021-09-18

基于vue2、vue-meta-info(0.1.7)和prerender-spa-plugin(3.4.0)

vue.config.js

const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
module.exports = {
    configureWebpack: config => {
        if (process.env.NODE_ENV !== 'production') return;
        return {
            plugins: [
                new PrerenderSPAPlugin({
                    staticDir: path.join(__dirname, 'dist'),
                    routes: ['/', '/rankingList'],
                    renderer: new Renderer({
                        inject: {
                            foo: 'bar'
                        },
                        headless: false,
                        renderAfterDocumentEvent: 'render-event'
                    })
                })
            ]
        }
    }
}

main.js

import MetaInfo from 'vue-meta-info'
Vue.use(MetaInfo)

new Vue({
  mounted () {
    document.dispatchEvent(new Event('render-event'))
  }
}).$mount('#app')

a.vue

export default {
  metaInfo: {
    title: "xxx | xxxxx",
    meta: [
      {
        name: "keywords",
        content: "xxxxxxxxx",
      },
      {
        name: "description",
        content: "xxxxxxxxxxxxxx",
      },
    ],
  },
}

异常处理

若main.js存在以下类似跳转链接(如:手机跳转PC),将出现打包后样式及JS丢失的问题(生成的html引用的文件名hash跟实际打包出来的不一样,应该是做了seo优化后打包预览时链接跳转导致)。
可以先将连接语句(location.href = “https://xxx.com” + window.location.pathname;)替换为(其他任何可以方便查找替换的内容),待打包完成后,再替换成正确的链接。

router.beforeEach((to, from, next) => {
  if (_isMobile()) {
    next();
  } else {
    location.href = "https://xxx.com" + window.location.pathname;
  }

  function _isMobile() {
    let flag = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    return flag;
  }
});
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值