Nuxt.js 生成sitemap站点地图文件
Nuxt.js 生成sitemap站点地图文件
背景介绍
使用nuxt框架生成静态文件支持SEO优化,打包之后需要生成一个 sitemap.xml 文件方便提交搜索引擎进行收录。官网有提供一个插件sitemap 但是如果是动态路由需要手动一个个配置比较麻烦,无法自动检索生成。所以自己编写一个生成 sitemap 模块
准备工作
创建nuxt项目,参考中文官网。安装JavaScript模板ejs工具
$ npm install ejs
相关网站
- 插件sitemap: https://sitemap.nuxtjs.org/
- 中文官网:https://www.nuxtjs.cn/
- 英文官网:https://v2.nuxt.com/
- JS模板工具ejs:https://github.com/mde/ejs
- 扩展模块:https://v2.nuxt.com/docs/directory-structure/modules
sitemap模块
项目根目录创建 modules 目录,以及对应文件,详细文件内容放在文末。
├─modules
│ └─robots.ejs // robots模板
│ └─sitemap.js // 站点地图js
│ └─template.ejs //sitemap 模板
配置 nuxt.config.js
在 modules 数组增加以下内容 modules/sitemap 刚才自定义模块,excludes 需要排除的目录,hostname 站点域名
nuxt.config.js
export default {
...省略
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
...省略,
['modules/sitemap',
{
excludes: ['_nuxt', 'img'],
hostname: 'https://www.example.com'
}
],
],
}
执行命令生成静态资源
$npm run generate
打开项目根目录下dist(默认输出路径),会多出两个文件
├─robots.txt
├─sitemap.xml
结果展示


官方示例 modules
编写自己的模块
模块就是函数。它们可以打包为 npm 模块或直接包含在项目源代码中。
nuxt.config.js
export default {
exampleMsg: 'hello',
modules: [
// Simple usage
'~/modules/example',
// Passing options directly
['~/modules/example', { token: '123' }]
]
}
modules/example.js
export default function ExampleModule(moduleOptions) {
console.log(moduleOptions.token) // '123'
console.log(this.options.exampleMsg) // 'hello'
this.nuxt.hook('ready', async nuxt => {
console.log('Nuxt is ready')
})
}
// REQUIRED if publishing the module as npm package
module.exports.meta = require('./package.json')
1) ModuleOptions
moduleOptions:modules 这是用户使用数组传递的对象 。我们可以用它来定制它的行为。
有时,如果我们可以在注册模块时使用顶级选项会更方便 nuxt.config.js。这使我们能够组合多个选项源。
nuxt.config.js
export default {
modules: [['@nuxtjs/axios', { anotherOption: true }]],
// axios module is aware of this by using `this.options.axios`
axios: {
option1,
option2
}
}
2) this.options
this.options:您可以使用此参考直接访问 Nuxt 选项。nuxt.config.js 这是分配有所有默认选项的用户内容 。它可用于模块之间的共享选项。
模块.js
export default function (moduleOptions) {
// `options` will contain option1, option2 and anotherOption
const options = Object.assign({}, this.options.axios, moduleOptions)
// ...
}
modules文件
modules/robots.ejs
# robots.txt
User-agent: Baiduspider
Disallow:
User-agent: Sosospider
Disallow:
User-agent: sogou spider
Disallow:
User-agent: YodaoBot
Disallow:
User-agent: Googlebot
Disallow:
User-agent: Bingbot
Disallow:
User-agent: Slurp
Disallow:
User-agent: Teoma
Disallow:
User-agent: ia_archiver
Disallow:
User-agent: twiceler
Disallow:
User-agent: MSNBot
Disallow:
User-agent: Scrubby
Disallow:
User-agent: Robozilla
Disallow:
User-agent: Gigabot
Disallow:
User-agent: googlebot-image
Disallow:
User-agent: googlebot-mobile
Disallow:
User-agent: yahoo-mmcrawler
Disallow:
User-agent: yahoo-blogs/v3.9
Disallow:
User-agent: psbot
Disallow:
Disallow: /bin/
Disallow: /js/
Disallow: /img/
Sitemap: <%= hostname %>/sitemap.xml
modules/sitemap.js
/**
* @description 生成 sitemap robots 模块
* @author 方圆百里
* @time 2023年10月12日
*/
const path = require('path');
const fs = require('fs');
const ejs = require('ejs');
/**
* @description 获取当前目录下载的所有路径 -同步
* @author 方圆百里
*
* @param {String} dir 文件路径
* @returns {Array} 返回路径数组
*/
const loadFiles = (dir) => {
try {
const data = fs.readdirSync(dir);
return data;
} catch (e) {
console.error('获取目录路径异常', e)
return undefined;
}
}
/**
* @description 获取文件信息
* @author 方圆百里
*
* @param {String} dir 文件路径
* @returns {Array} 返回路径数组
*/
const statFile = (full_path) => {
try {
const stat = fs.statSync(full_path);
stat.path = full_path;
return stat;
} catch (e) {
console.error('获取目录路径异常', e)
return undefined;
}
}
/**
* @description 递归处理文件路径
* @author 方圆百里
*
* @param {String} dir 文件路径
* @param {String} list 文件信息数组
* @returns {Array} 返回路径数组
*/
const handleFiles = (dir, list = [], excludes) => {
// 1、加载当前目录下所有路径,包含文件夹和文件
const data = loadFiles(dir);
if (data) {
data.forEach(item => {
if (!excludes.includes(item)) {
// 2、拼接绝对路径
const absolutePath = path.join(dir, item)
// 3、获取文件基本信息
const stat = statFile(absolutePath);
// 4、如果是文件,处理基本信息
if (stat.isFile()) {
list.push({
size: stat.size,
time: stat.ctime,
...path.parse(stat.path)
})
} else { // 5、目录递归进行处理
handleFiles(stat.path, list, excludes);
}
}
})
}
return list;
}
/**
* @description 格式化日期
* @author 方圆百里
*
* @param {Date} date 日期
* @returns {String} 2023-10-12
*/
const formatYear = (date) => {
// 获取年、月和日
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始,需要加1,同时确保两位数格式
const day = date.getDate().toString().padStart(2, '0'); // 确保两位数格式
// 格式化日期
return `${year}-${month}-${day}`;
}
/**
* @description 生成站点地图
* @author 方圆百里
*
* @param {String} dist 打包后文件路径
* @param {String} hostname 主机名称
* @param {Array} excludes 排除路径
*
*/
const generateSitemap = (dist, hostname, excludes) => {
const data = handleFiles(dist, [], excludes)
const set = new Set();
for (var i = 0; i < data.length; i++) {
const f = data[i];
if (f.ext === '.html') {
const relative = f.dir.replace(dist, "")
if (relative) {
const paths = relative.split(path.sep);
let loc = hostname;
for (var x = 1; x < paths.length; x++) {
loc += "/" + paths[x];
}
set.add({
loc: loc,
time: formatYear(f.time)
});
}
}
}
// 读取模板文件
const template = fs.readFileSync('modules/template.ejs', 'utf-8');
// 提供模板数据
const datas = {
urls: set
};
// 使用模板引擎渲染模板
const renderedContent = ejs.render(template, datas);
// 写入生成的文件
fs.writeFileSync(path.join(dist, 'sitemap.xml'), renderedContent);
console.log('sitemap.xml 生成成功!');
const robotsRendered = ejs.render(fs.readFileSync('modules/robots.ejs', 'utf-8'), {
hostname
});
// 写入生成的文件
fs.writeFileSync(path.join(dist, 'robots.txt'), robotsRendered);
console.log('robots.txt 生成成功!');
}
export default function ExampleModule(moduleOptions) {
const dist = this.options.generate?.dir || 'dist'; // 打包输出路径
const hostname = moduleOptions.hostname || 'https://www.example.com'; // 主机名称
const excludes = moduleOptions.excludes || ['.nuxt']; // 排除路径
console.log('打包输出路径:=====>', dist)
console.log('主机名称:=====>', hostname)
console.log('排除路径:=====>', excludes)
this.nuxt.hook('generate:done', async generator => {
// 这将在Nuxt生成页面之之后调用
console.log('执行 generate 完成')
generateSitemap(dist, hostname, excludes)
})
}
// 将模块发布为npm包
module.exports.meta = require('../package.json')
modules/template.ejs
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<% urls.forEach(function(item) { %>
<loc><%= item.loc %></loc>
<lastmod><%= item.time %></lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
<% }); %>
</url>
</urlset>
Nuxt.js 生成sitemap站点地图文件的更多相关文章
- php生成百度站点地图sitemap.xml
<?php header("Content-type:text/html;charset=utf-8"); //php生成百度站点地图sitemap.xml //http:/ ...
- WordPress免插件生成完整站点地图(sitemap.xml)的php代码
让这个代码更加完善,可以同时生成首页.文章.单页面.分类和标签的 sitemap! 一.PHP 代码 <?php require('./wp-blog-header.php'); header( ...
- Hexo优化 | 创建sitemap站点地图并向Google提交
前言 站点地图是一种文件,您可以通过该文件列出您网站上的网页,从而将您网站内容的组织架构告知Google和其他搜索引擎.Sitemap 可方便管理员通知搜索引擎他们网站上有哪些可供抓取的网页.搜索引擎 ...
- Java生成sitemap网站地图
访问我的博客 sitemap 是什么?对应没有接触过网站 SEO 的同学可能不知道,这里引用一下百度站长的一段解释. Sitemap(即站点地图)就是您网站上各网页的列表.创建并提交Sitemap有助 ...
- Django:之Sitemap站点地图、通用视图和上下文渲染器
Django中自带了sitemap框架,用来生成xml文件 Django sitemap演示: sitemap很重要,可以用来通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录. 开启si ...
- SEO优化:WordPress站点地图(html和xml)插件Baidu Sitemap Generator
前阵子分享了<如何实现纯代码制作网站地图的html和xml版本>,不过不是每个人都喜欢用纯代码来折腾博客的.今天,boke112就给大家分享一款国人柳城制作的包含html和xml两个版本的 ...
- 关于ASP.NET 中站点地图sitemap 的使用
在ASP.NET MVC 如此火热的时期,我竟然不适时宜的谈起ASP.NET ,恐怕会引来一阵嘲笑.最为无趣的是,讲解的竟然还是其中的一个控件.oh~~ my god!my out! ^_^ Si ...
- 使用windows服务更新站点地图
由于公司平台访问人数逐渐增多,公司项目的数据库已经几次出现宕机现象.为减轻数据库压力,我上个月对公司项目做了下调整.把新闻板块提取出来单独一个站点,单独一个数据库.减少了主站点和数据库的负担和压力. ...
- 从壹开始 [ Nuxt.js ] 之二 || 项目搭建 与 接口API
前言 哈喽大家周一好,今天的内容比较多,主要就是包括:把前端页面的展示页给搭出来,然后调通接口API,可以添加数据,这两天我也一直在开发,本来想一篇一篇的写,发现可能会比较简单,就索性把项目搭建的过程 ...
- 在Vue&Element前端项目中,使用FastReport + pdf.js生成并展示自定义报表
在我的<FastReport报表随笔>介绍过各种FastReport的报表设计和使用,FastReport报表可以弹性的独立设计格式,并可以在Asp.net网站上.Winform端上使用, ...
随机推荐
- 脚手架服务运行 报错 error:03000086:digital envelope routines::initialization error
报错图片 解决方法: 降低版本 https://nodejs.org/zh-cn/ 安装后(安装前先卸载高版本,点击左下放大镜搜索"卸载程序" 进行卸载) 安装完成后,再次回到vu ...
- hexo博客yilia主题_缺失模块_解决方案
hexo博客yilia主题,左侧栏目有一个全部文章的按钮,刚开始开始报错缺失模块,如下图: 我解决了这个问题着实不容易饶了弯路,但是跟着提示步骤,其实很简单,走起: 1.查看node版本 win键+R ...
- 【转载】Linux虚拟化KVM-Qemu分析(十)之virtio驱动
原文信息 作者:LoyenWang 出处:https://www.cnblogs.com/LoyenWang/ 公众号:LoyenWang 版权:本文版权归作者和博客园共有 转载:欢迎转载,但未经作者 ...
- Composer 镜像原理 (1) —— 初识 Composer
相关文章 Composer 镜像原理 (1) -- 初识 Composer Composer 镜像原理 (2) -- composer.json Composer 镜像原理 (3) -- 完结篇 何为 ...
- 抽象语法树AST必知必会
1 介绍 AST 打开前端项目中的 package.json,会发现众多工具已经占据了我们开发日常的各个角落,例如 JavaScript 转译.CSS 预处理.代码压缩.ESLint.Prettier ...
- CobaltStrike4.8--云服务器搭建
系统版本选用 选择最熟悉的版本,我这边用的CentOS7.8,选用乌班图的话,会有一些命令的不一致 配置运行环境 CobaltStrike4.0支持jdk1.8的环境,4.5开始就不支持1.8了,本文 ...
- Element-ui源码解析(一):项目目录解析
开始看原码了,我们要开始一些准备工作, 既然是拆代码,那么我们要先把代码搞到手 1.如何下载原码 随便开个项目 npm i element-ui -S 将源码下载到本地 随后在node_module ...
- 超越.NET极限:我打造的高精度数值计算库
超越.NET极限:我打造的高精度数值计算库 还记得那一天,我大学刚毕业,紧张又兴奋地走进人生第一场.NET工作面试.我还清楚地记得那个房间的气氛,空调呼呼地吹着,面试官的表情严肃而深沉.我们进行了一番 ...
- CGLIB动态代理对象GC问题排查
一.问题是怎么发现的 最近有个新系统开发完成后要上线,由于系统调用量很大,所以先对核心接口进行了一次压力测试,由于核心接口中基本上只有纯内存运算,所以预估核心接口的压测QPS能够达到上千. 压测容器配 ...
- 《VTK图形图像开发进阶》第1-2章——一个稍微复杂的VTK程序
VTK概览 数据可视化主要是通过计算机图形学的方法,以图形.图像等形式清晰有效地传递.表达信息,VTK是数据可视化的工具包. VTK全称(Visualization Toolkit),即可视化工具包, ...