Skip to content

Instantly share code, notes, and snippets.

@darkcris1
Last active January 1, 2021 11:02
Show Gist options
  • Save darkcris1/b5c0e5c4e43cc7558c67c55d2fad0fcf to your computer and use it in GitHub Desktop.
Save darkcris1/b5c0e5c4e43cc7558c67c55d2fad0fcf to your computer and use it in GitHub Desktop.
Generate a file paths in next.js | This is useful if you are using getStaticPaths
import fs from 'fs'
const ignoreRegex = /_(.*?).md/
const isMd = (value) => /\.md$/.test(value)
function generateMdPaths(data, currentPath = '', ext = '') {
return data.reduce((acc, value) => {
if (ignoreRegex.test(value)) return acc
if (!isMd(value)) {
const path = `${currentPath}/${value}/`
const data = fs.readdirSync(path)
// return immediately if directory is empty
if (data.length === 0) return acc
// recursively generate tree files
acc.push(...generateMdPaths(data, path, `${ext}${value}/`))
} else {
// Convert into array since it was a spread dynamic page
const slug = (ext + value.replace(/\.md$/, '')).split('/')
acc.push({ params: { docs: slug } })
}
return acc
}, [])
}
export default generateMdPaths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment