- Java锁的逻辑(结合对象头和ObjectMonitor)
- 还在用饼状图?来瞧瞧这些炫酷的百分比可视化新图形(附代码实现)⛵
- 自动注册实体类到EntityFrameworkCore上下文,并适配ABP及ABPVNext
- 基于Sklearn机器学习代码实战
使用 nuxt 框架生成静态文件支持SEO优化,打包之后需要生成一个 sitemap.xml 文件方便提交搜索引擎进行收录。官网有提供一个插件 sitemap 但是如果是动态路由需要手动一个个配置比较麻烦,无法自动检索生成。所以自己编写一个生成 sitemap 模块 。
创建 nuxt 项目,参考 中文官网 。安装 JavaScript 模板ejs工具 。
$ npm install ejs
项目根目录创建 modules 目录,以及对应文件,详细文件内容放在文末.
├─modules
│ └─robots.ejs // robots模板
│ └─sitemap.js // 站点地图js
│ └─template.ejs //sitemap 模板
在 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
模块就是函数。它们可以打包为 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')
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
}
}
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/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站点地图文件的文章就讲到这里了,如果你想了解更多关于Nuxt.js生成sitemap站点地图文件的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我从这里复制了一些文件:https://codesandbox.io/s/github/nuxt/nuxt.js/tree/dev/examples/custom-loading?from-embed
我已经在整个互联网上搜索了我的问题的答案。到目前为止没有运气。 我想要达到的目标: 我有一个在通用模式下运行的 Nuxt 应用程序。它类似于一个小型社交网络,用户可以在其中创建自己的个人资料并分享他们
在我的 nuxt 应用程序中,嵌套目录中的组件不会按预期自动导入。对于我的一些组件,我有如下内容:vue 2.6.12 , nuxt 2.15.0components\目录结构 TopArea\ --
我有点困惑,因为在官方 nuxt 网站上它说当前的 nuxt 版本是 2.5.X 但是当我使用 npx create-nuxt-app 创建 nuxt 应用程序时并检查 package.json在依赖
我有survey-vue(surveyJS)在dev上运行良好,但是当我尝试部署时,登陆带有调查组件的页面时出现最大调用堆栈大小超出错误。 我在想这就是我导入插件的方式,但我不确定。 插件/surve
我有如下路径 路径:'/board/:type(\d{2}):subtype(\d{2}):id(\d+)' 所以这是这样的 http://localhost:3000/board/112233333
我构建多应用 Nuxt 项目,这些应用之间不直接通信。每个应用程序都有自己的商店,我想为共享商店使用一个目录。我将这种方法用于组件并且效果很好。 |-> app1 | |-> store // s
将我的 nuxt-cli 版本升级到 2.15.3 后,我注意到页面 block 的大小减小了,所有 node_modules 安装的包现在都被捆绑到现在变得越来越大的 app.js 中。 在下面你可
我正在使用 nuxt 生成完整的静态 Web 应用程序,如下所述 https://nuxtjs.org/blog/going-full-static/#crazy-fast-static-applic
我已经看到很多与此主题相关的问题。但是他们都没有解决我的问题。 我有一个情况,我必须检查 innerWidth窗口,使用 isMobile 检查设备是否可移动多变的。 ...
我在最新版本的 Vuetify 中使用 NuxtJs。 在我的导航栏中有一个通向主页的主页按钮,这是它的代码: mdi-home 只要我在主页上,图标就会悬停: 一旦
我有一个登录页面,我希望登录的用户无法看到。我的组件如下: ... ... @Component({ layout: 'fullWidth', auth: '
我正在创建一个插件,它将发出由套接字触发的基本 nuxt 事件。然后将收到 nuxt 事件并打开一个 snackbar 。在组件内部时,使用 $nuxt 可以轻松发送和接收事件。 this.$nuxt
我有一个Composable,它返回一个函数,在5秒的间隔内验证身份验证和刷新令牌。两者都利用Nuxt的useCookie实用程序函数来执行其背后的逻辑。。起初,它是有效的。但有时,当令牌到期时,它会
我不能在这里使用 window.location,因为它是 SSR 应用程序。useRouter、useRoute 和 useNuxtApp 也没有域名。nuxtApp.ssrContext 未定义。
我在 nuxt.js 上有前端服务器,在带有 django-rest-framework 的 django 中有后端。谁能给我一个使用 nuxt-auth 本地策略刷新 jwt token 的例子?我
有很多关于 Nuxt SSR 或全静态的信息,但我找不到任何指南如何构建具有静态页面的混合 SSR。 我正在使用 Nuxt SSR 构建一个网站,我想从一个 10MB 的 JSON 文件静态预渲染所有
我在本地构建了nuxt js的项目,即npm run build,然后将项目推送到.nuxt文件夹,而不是node_modules文件夹。然后运行npm run start命令,失败。 输出信息:sh
我有一个 NUXT 项目,我正在尝试添加 301 重定向。我尝试了几种不同的方法,但没有任何效果。如果我转到旧 URL,我会得到一个 404 页面。 向 Nuxt 项目添加重定向的最佳方式是什么? 任
我正在使用 Nuxt Content存储应用程序内容(JSON 文件)。它在热重载的开发模式下工作很酷。我网站的后端更改内容文件夹中的任何文件,并且这会立即在浏览器中更改而无需重新加载页面。但在生产模
我是一名优秀的程序员,十分优秀!