Last active
January 1, 2021 11:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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