更新于:2021-09-18
Vue的seo优化
基于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;
}
});
本文介绍了在Vue2项目中进行SEO优化的方法,包括使用vue-meta-info和prerender-spa-plugin,并针对打包后样式和JS丢失的问题提供了解决方案,即在main.js中的特定跳转链接在打包时做临时替换,待打包完成后再恢复。
3368

被折叠的 条评论
为什么被折叠?



