背景
项目上要求增强SEO效率,但是由于项目最初并未使用Nuxt做SSR,因此只能退而求其次采用预渲染的方式来解决此问题
选择插件
这里选择的是 @prerenderer/webpack-plugin
插件,之所以没有选用prerender-spa-plugin
,主要是因为prerender-spa-plugin
在webpack5下有bug,另一个原因是 @prerenderer/webpack-plugin
这个插件更官方一些
集成步骤
1. 安装插件
// 安装预渲染插件
npm i -D @prerenderer/webpack-plugin @prerenderer/renderer-puppeteer
// 用来写meta描述
npm i vue-meta-info
2. 修改main.js
// 引入并使用metainfo插件
import MetaInfo from 'vue-meta-info';
Vue.use(MetaInfo);
// 添加预渲染事件
new Vue({
el: '#app',
router,
store,
mounted() {
document.dispatchEvent(new Event('render-event'));
},
render: (CreateElement) => CreateElement(App),
});
3. 修改vue.config.js
// 引入预渲染插件
const path = require('path');
const PrerendererWebpackPlugin = require('@prerenderer/webpack-plugin');
// 打包配置
configureWebpack: {
plugins: [
new PrerendererWebpackPlugin({
staticDir: path.join(__dirname, 'dist'), // 静态资源目录
routes: ['/tourist'], // 需要预渲染的路由
rendererOptions: {
renderAfterDocumentEvent: 'render-event', // 这个事件名与main.js中的事件名保持一致
},
// 除了使用插件,meta也可以动态加,与第五步任选一种
postProcess: function (context) {
var titles = {
'/tourist': {
title: '测试title',
keywords: '测试keywords',
description: '测试description'
},
}
context.html = context.html.replace(
/<title>[^<]*<\/title>/i,
'<title>' + titles[context.route].title + '</title>'
)
context.html = context.html.replace(
/<meta name="keywords" content="[^"]*"/i,
'<meta name="keywords" content="' + titles[context.route].keywords + '"'
);
context.html = context.html.replace(
/<meta name="description" content="[^"]*"/i,
'<meta name="description" content="' + titles[context.route].description + '"'
)
}
}),
],
},
4. 修改router.js
// 引入页面/组件
import DefaultLayout from '@/layout/DefaultLayout.vue';
import TouristHome from '@/views/tourist/index.vue';
// 定义路由
const routes = [
{
path: '/',
name: 'Main',
component: DefaultLayout,
children: [
{
path: 'tourist',
name: 'TouristHome',
// component: () => import('@/views/tourist/index.vue'), // 经尝试,这种懒加载的方式无效
component: TouristHome
}
]
}
]
注意:路由模式一定要是history模式,hash模式无效
5. 给预渲染页面增加meta
// tourist.vue
<script>
export default {
name: 'TouristHome',
metaInfo: {
title: '游客空间',
meta: [
{
name: 'keyWords',
content: '游客空间关键字',
},
{
name: 'description',
content: '游客空间描述',
},
],
},
};
</script>
6. 效果与验证
以上就是基本配置的步骤,使用 npm run build 打包后目录如图
之后在浏览器打开这个index.html查看源码,只要meta标签有刚才我们写入的信息就算是ok了
小结
虽说该方案一定程度上能解决SEO问题,但是依然是具有以下两个缺点
- 需要在vue.config.js中配置大量路由
- MetaInfo中的关键字不能通过接口获取,只能在最初定义好
因此最佳的解决SEO方案还是使用SSR(服务端渲染)