Skip to content

Instantly share code, notes, and snippets.

@davay42
Last active April 9, 2021 08:18
Show Gist options
  • Save davay42/fc90eafe236f873b4110f7f913e10934 to your computer and use it in GitHub Desktop.
Save davay42/fc90eafe236f873b4110f7f913e10934 to your computer and use it in GitHub Desktop.
Vitepress pages tags collections
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import { glob } from 'glob'
export function getTags(dir = '../../pages', pattern = '/**/*.md') {
const pageDir = path.resolve(__dirname, dir)
const filesList = glob.sync(pageDir + pattern, { nodir: true })
const tags = {}
const all = filesList.map((file) => {
let info = matter(fs.readFileSync(path.resolve(pageDir, file), 'utf8'))
let data = {
title: info.data?.title,
url:
dir.split('/').pop() +
'/' +
path.relative(pageDir, file).split('.').shift(),
data: info?.data,
}
if (typeof info?.data?.tags == 'string') {
let tag = info?.data?.tags
tags[tag] = tags[tag] || []
tags[tag].push(data)
}
if (Array.isArray(info.data?.tags) && info?.data?.tags.length > 0) {
info.data.tags.forEach((tag) => {
tags[tag] = tags[tag] || []
tags[tag].push(data)
})
}
return data
})
return { all, ...tags }
}
@davay42
Copy link
Author

davay42 commented Apr 8, 2021

This small script recursively takes all the .md files in the given directory, parses their frontmatter and creates collections of the pages based on 'tags' lists. It may be used to create any kind of navigation for vitepress. It works fine when just imported into the vitepress config and added to 'customData' property there customData: { skills: getTags('../../skills') }. I need help making it a proper npm package – I'm not a node xpert and can't figure out the exact build setup configuration for that.

@davay42
Copy link
Author

davay42 commented Apr 9, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment