Vue使用sitemap-webpack-plugin根据路由地址生成sitemap.xml

2,382 阅读2分钟

「这是我参与2022首次更文挑战的第20天,活动详情查看:2022首次更文挑战」。

Sitemap.xml

Sitemap.xml,相信大家都知道是什么了:站点地图。

由Google最先发起。利用Sitemaps协议,网站管理员可以列出网站上可以供搜索引擎抓取的URL,并通知给后者。

Sitemaps中包含有关每个URL的其他信息,如:URL上次更新的时间更新的频率以及相对于网站其他URL的重要性。搜索引擎的爬虫可以通过Sitemaps更有效地抓取网站内容,并找到可能与网站其他内容没有相互链接的URL。Sitemaps协议是对robots.txt的补充。

比如B站的sitemap.xml

B站的sitemap.xml

我博客的sitemap.xml

我博客的sitemap.xml

而今天,我们来试试Vue项目如何生成sitemap.xml,首先看看sitemap.xml主要内容。

<loc>

sitemap.xml内有着<loc>属性。内部为网址(站点具体内容),此网址应以协议开始(例如:http)并以斜线结尾。此值应少于 2048 个字符。

<lastmod>

可选标签;标签含义:该文件上次修改的日期。此日期应采用 W3C Datetime 格式。如果需要的话,此格式允许省略时间部分,而仅使用 yyyy-MM-DD。 列子:2022-02-06

<changefreq>

可选标签;链接更新频率。

工具选择

首先,Vue项目的路由需要为history模式

history模式

相比Hash模式这样生成的sitemap.xml更容易收录。

其次,之前有看过这篇文章:zigamiklic.com/simple-site…

其中getRoutesXML

function getRoutesXML() {
	const list = getRoutesList(router.options.routes, 'https://zigamiklic.com')
		.map(route => `<url><loc>${route}</loc></url>`)
		.join('\r\n');
	return `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
    ${list}
  </urlset>`;
}

可以根据路由对象,拼接主域名,进而返回sitemap内容。

可以放到路由内用console.log(getRoutesXML())打印输出,并到浏览器内F12进行复制创建sitemap.xml。

但是有点不方便;怎么让Vue项目在打包时候就自动生成sitemap.xml呢?

答案是:sitemap-webpack-plugin

sitemap-webpack-plugin

sitemap-webpack-plugin项目地址:github.com/schneidmast…

新版本目前支持webpack4+,自然支持我们的Vue项目。

安装

安装方法相当简单,因为我们只是在打包时候使用,所以可以加上-D参数:

npm i sitemap-webpack-plugin -D

安装成功

之后就是配置vue.config.js了。

配置Vue.config.js

首先,我们定义一个数组,数组内就是sitemap.xml内的想生成的<loc>

let routes = [
  '/', '/processIMG', '/statisticsChars', '/generatePWD', '/calculateTheDate',
  '/randomNumber', '/textBase64', '/curl', '/mcstatus',
  '/gh', '/about', '/mdv'
]

路由数组

之后,根据官方文档,我们使用链式函数:

config.plugin("sitemap").use(sitemapWebpackPlugin, [
  {
    base: 'https://tool.mintimate.cn',
    paths: routes,
    options: {
      # 生成的站点地图文件名
      filename: 'sitemap.xml',
      # lastMod属性是否开启
      lastMod: true,
      # 更新频率
      changefreq: 'monthly'
    },
  }
])

配置Vue.config.vue

打包

最后,我们打包即可:

npm run build

打包成功

END

使用sitemap-webpack-plugin生成sitemap.xml还是很简单的。有什么问题欢迎评论区留言嗷。

生成好的sitemap.xml就可以到站点管理里上传了嗷。