Skip to content

Instantly share code, notes, and snippets.

@AmyrAhmady
Last active March 7, 2021 11:36
Show Gist options
  • Save AmyrAhmady/7d6f3c8c617faa062a5b6e66ddc7c59a to your computer and use it in GitHub Desktop.
Save AmyrAhmady/7d6f3c8c617faa062a5b6e66ddc7c59a to your computer and use it in GitHub Desktop.
Docusaurus sidebar generator by name of directories and files!
const fs = require("fs");
const path = require('path');
const SIDE_BAR_NAME = 'Sidebar';
const CATEGORY_NAME_CAPITALIZATION = true;
function parseDir(filename) {
const stats = fs.lstatSync(filename);
const info = {}
// check if it's a directory
if (stats.isDirectory()) {
// if it's `docs` directory, set it as main and first key
if (path.basename(filename) === 'docs') {
info[SIDE_BAR_NAME] = fs.readdirSync(filename).map(function (child) {
return parseDir(filename + '/' + child);
});
}
// it's a directory inside `docs` folder
else {
info.type = 'category'
const catName = path.basename(filename);
if (CATEGORY_NAME_CAPITALIZATION) {
info.label = catName.charAt(0).toUpperCase() + catName.substring(1);
} else {
info.label = catName;
}
info.items = fs.readdirSync(filename).map(function (child) {
return parseDir(filename + '/' + child);
});
}
}
// it's a file, so it should be path/to/file starting in `docs` directory as root
else {
// remove `filename.md` and `docs/`
const tmpPath = filename.split("/");
tmpPath.pop();
tmpPath.splice(0, 1);
let docPath = '';
tmpPath.map((name) => docPath = docPath + name + '/');
return docPath + path.basename(filename).replace('.md', '');
}
return info;
}
module.exports = parseDir('docs');
@kovetskiy
Copy link

Thanks, this saved a lot of time for me!

@AmyrAhmady
Copy link
Author

glad to hear that!

@batkiz
Copy link

batkiz commented Mar 7, 2021

This code doesn't handle the .mdx files, if you want to use them, change

    return docPath + path.basename(filename).replace('.md', '');

to

    if (path.basename(filename).endsWith('mdx')) {
      return docPath + path.basename(filename).replace('.mdx', '');
    }
    return docPath + path.basename(filename).replace('.md', '');

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