前言
vue属于单页面应用,对于SEO不太友好,当然vue也给出了相应的解决办法,可以通过vue ssr服务端渲染进行解决,但对于页面较少的企业站来说可以直接使用 prerender-spa-plgin,本文总结prerender-spa-plugin+vue-meta-info做seo优化及遇到的问题。
一、prerender-spa-plugin使用
vue版本2.6.12
webpack4.0
1.安装
//npm
npm install prerender-spa-plugin --save
//yarn
yarn add prerender-spa-plugin --dev
2.vue.config.js配置
const PrerenderSPAPlugin = require('prerender-spa-plugin');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
//配置绝对路径
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
configureWebpack: config=> {
//在开发环境不进行预渲染操作
if(process.env.NODE_ENV === 'production'){
const plugins=[
new PrerenderSPAPlugin({
//根目录
staticDir: resolve('dist'),
//需要预渲染的路由
routes:['/','/about','/contact'],
renderer: new Renderer({
ignoreJSErrors: true,
inject: {
foo: 'bar'
},
//渲染时显示浏览器窗口,建议直接为true
headless: true,
//最大渲染路由数量
maxConcurrentRoutes:20,
//延迟多长时间进行渲染
renderAfterTime: 5000,
//main.js中进行对应配置
renderAfterDocumentEvent: 'render-event'
})
})
]
config.plugins.push(...plugin)
}
}
}
3.main.js配置
new Vue({
el: '#app',
store,
router,
render: h => h(App),
//重要部分
mounted () {
document.dispatchEvent(new Event('render-event'))
}
})
4.router.js中一定要设置history模式
export default new Router({
mode: 'history', // 路由模式
routes: constantRoutes,
})
5.npm run build
打包之后可以看到配置好的路由生成了相应的html页面
269b23c7c40644e386393c1c5fe8f1b5.jpeg
二、vue-meta-info使用
1.安装
npm install vue-meta-info --save
2.main.js引用
import MetaInfo from 'vue-meta-info'
// 注册
Vue.use(MetaInfo)
3.页面使用
//单个页面配置
<template>
<div>首页</div>
</template>
export default {
name:'首页'
metaInfo:{
title:'首页',
meta:[
{
name: 'keyWords',
content:'关键字'
},
{
name:'description',
content:'描述'
}
]
}
}
//多页面配置
<template>
<div>首页</div>
</template>
export default {
name:'index'
metaInfo():{
return{
meta:this.metaData
}
},
data(){
return{
metaData:''
}
},
watch:{
$route(to,form){
//通过跳转页面配置每个页面的关键字和描述,这只是个例子
//注意如果通过to.path去判断 需要进行兼容判断 因为渲染后的访问路径会在末尾自动添加/ 例如 loclhost:3000/index/,这个时候就需要 to.path === '/index' || to.path==='/index/'
if(to.name === 'index'){
this.metaData=[
{
name: 'keyWords',
content:'关键字'
},
{
name:'description',
content:'描述'
}
]
}
//当然也可以封装一个方法去返回每个页面的文案
//this.metaData = metaSetFuc(to.name)
}
}
}
三、在使用中遇到的问题
1. [prerender-spa-plugin] Unable to prerender all routes! 错误
在node_modules -> @prerender -> renderer-puppeteer -> es6 -> renderer.js(113行)
await page.goto(`${baseURL}${route}`, navigationOptions);
//修改为
await page.goto(`${baseURL}${route}`, {...navigationOptions, timeout: 0});
2.修改完成之后一直处于build状态打包并未成功
检查一下index.html中是否存在引用外部css/js文件,因为在打包过程中未能拉取外部文件内容导致一直处于build状态,例如
<head>
//这种形式引用思源黑体字体库
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto+Sans+SC:100,300,400,500,700,900">
</head>
3.假如项目中用到了swiper,也许会产生一个问题进行预渲染后,swiper-slide渲染了个默认800px的宽度,导致刷新页面轮播图样式显示异常,暂时只能手动修改打包后的文件如果有解决办法欢迎留言
使用webpack5可以看一下: prerender-spa-plugin-next