elma.dev - Can ELMA 10月02日 20:52
Markdown文件排序与Nuxt配置
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍如何使用Nuxt.js对Markdown文件进行日期排序和路径优化,通过配置nuxt.config.js实现文件名的规范化。

If you are using static site generators, you will be dealing with Markdown files with the .md extension. Confusion arises especially as the number of .md files increases.

For example, let's see the following example:

├── daphne-gunicorn.md├── just-a-command-runner.md└── django-serve-txt.md

Wouldn't it be better if it was as below:

├── 2021-07-30--daphne-gunicorn.md├── 2021-07-31--just-a-command-runner.md└── 2021-08-07--django-serve-txt.md

The order is now more apparent, and we can easily see at a glance which files belong to which year or month. Now I will explain how we can create this structure in Nuxt.

Let's start by making the following change.

nuxt.config.js
export default {  hooks: {    // 2021-12-12--post-slug > post-slug    'content:file:beforeInsert': (document) => {      if (document.extension === '.md') {        const regex = /^(\d{4}-\d{2}-\d{2})--/g        if (document.slug.match(regex)) {          document.slug = document.slug.replace(regexpRule, '')        }      }    },  },}

Now Nuxt will automatically remove the leading date when creating the slug for these files.

This change necessitates another minor change. Normally, when visiting the path /notes/daphne-gunicorn, we would find the corresponding file inside the notes folder using the slug part (daphne-gunicorn) of that path:

const note = await $content('notes', params.slug)

This is no longer possible as the relation between the slug and the filename is corrupted due to the change we made. We can solve this. You should fetch the content as below:

const [note] = await $content('notes')  .where({ slug: params.slug })  .limit(1)  .fetch()

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Nuxt.js Markdown 文件排序 路径优化
相关文章