(The VuePress version used by the blogger is 1.x, please pay attention to your own version first,2.x can be used if you are not sure)

As mentioned above, like most programmers, bloggers occasionally like to write documents. As they get older, they can’t remember many things, so it is more practical to write them out.

I have been using VuePress for a long time and creating automation for a long time (one or two years). Today, I have nothing to do. I have done some work and made an article, hoping to help people in need

To stay on topic, I don’t want to bother with the documentation. Most people just search for a good tutorial.

Don’t ask me why I didn’t publish to NPM (lazy and unnecessary)

Don’t ask if the Nav can be automated (don’t ask for requirements)

Don’t say what you can’t use (women stay on wechat, men strive to improve themselves)

File directory

Let’s take a look at my file directory

There are two main files used this time, utils/index.js and config.js(this configuration file is the official configuration file of Vuepress).

Don’t ask me why the file name of the root directory is not docs, but SRC (can be changed, didn’t you know?). You can refer to my directory structure to change (all optional)

Use the code

utils/index.js

const PATH = require('path')
const fs = require('fs')

// String utility class
const str = {
    /** * Whether two strings are the same *@param {String} String The first string *@param {String} Substr The second string *@param {Boolean} IsIgnoreCase Whether to ignore case *@returns {Boolean} Same is true, different is false */
    contains: (string, substr, isIgnoreCase) = > {
        // Convert the size to lowercase
        if (isIgnoreCase) {
            // toLowerCase() : converts the string toLowerCase
            string = string.toLowerCase()
            substr = substr.toLowerCase()
        }
        // Intercepts a single character
        let startChar = substr.substring(0.1)
        // Get the length of the string
        let strLen = substr.length
        for (let i = 0; i < string.length - strLen + 1; i++) {
            // charAt() : returns the character at the specified position
            if (string.charAt(i) === startChar) {
                // If the two strings from I are the same, they are the same
                if (string.substring(i, i + strLen) === substr) { return true}}}return false}}/** * Custom sort folder *@param  a
 * @param  b
 * @returns  { number }* /

function sortDir (a, b) {
    let al = a.parent.toString().split("\ \").length
    let bl = b.parent.toString().split("\ \").length
    if (al > bl) {
        return -1
    }
    if (al === bl) {
        return 0
    }
    if (al < bl) {
        return 1}}// File assistant
const filehelper = {
    / * * * *@param {String} Rpath Directory path *@param {Array} UnDirIncludes Some directories (folders) to be excluded *@param {Array} SuffixIncludes File name suffix *@returns * /
    getAllFiles: (rpath, unDirIncludes, SuffixIncludes) = > {
        let filenameList = []
        fs.readdirSync(rpath).forEach((file) = > {
            let fileInfo = fs.statSync(rpath + '\ \' + file)
            if(fileInfo.isFile() && ! unDirIncludes.includes(file) && ! str.contains(file,"img".true)) {
                // Only files with fixed suffixes are processed
                if (SuffixIncludes.includes(file.split('. ') [1]) {// Filter the readme.md file
                    if (file === 'readme.md' || file === 'README.md') {
                        file = ' '
                    } else {
                        // Intercepts the MD file suffix
                        file = file.replace('.md'.' ')
                    }
                    filenameList.push(file)
                }
            }
        })
        / / sorting
        filenameList.sort()
        return filenameList
    },
    / * * * *@param {String} Mypath Current directory path *@param {Array} UnDirIncludes Some directories (folders) to be excluded *@returns {Array} Result All directories */
    getAllDirs: function getAllDirs (mypath = ".", unDirIncludes,) {
        // Get directory data
        const items = fs.readdirSync(mypath)
        let result = []
        // Walk through all folders in the directory
        items.map(item= > {
            let temp = PATH.join(mypath, item)
            // isDirectory() takes no arguments and returns true if it is a directory (folder), false otherwise
            // If it is a directory and does not contain the following directories
            if(fs.statSync(temp).isDirectory() && ! item.startsWith(".") && !unDirIncludes.includes(item)) {
                result.push(mypath + '\ \' + item + '\ \')
                result = result.concat(getAllDirs(temp, unDirIncludes))
            }
        })
        return result
    }
}

// Sidebar creation tool
const sideBarTool = {
    /** * Create a sidebar that supports multilevel recursion *@param {String} RootPath Directory path *@param {Array} UnDirIncludes Some directories (folders) to be excluded *@param {Array} SuffixIncludes File name suffix *@returns {Object} Returns an object, as shown in the following {* * * '/ view/GFW: [' index'], * '/ view/git: [' index'], * '/ view/HTML / : [ 'day1', 'day2', 'day3', 'day4', 'day5' ], * } * */
    genSideBar: (RootPath, unDirIncludes, SuffixIncludes) = > {
        let sidebars = {}
        let allDirs = filehelper.getAllDirs(RootPath, unDirIncludes)
        allDirs.forEach(item= > {
            let dirFiles = filehelper.getAllFiles(item, unDirIncludes, SuffixIncludes)
            let dirname = item.replace(RootPath, "")
            dirname = dirname.replace(/\\/g.'/')
            if (dirFiles.length > 0) {
                sidebars[dirname] = dirFiles
            }
        })
        return sidebars
    },
    /** * Create a sidebar (with grouping) that supports multilevel recursion *@param {String} RootPath Directory path *@param {Array} UnDirIncludes Some directories (folders) to be excluded *@param {Array} SuffixIncludes File name suffix *@param {Object} Param3 Is not currently used (grouping related configuration parameters) *@returns {Array} Return an array as follows * [{* "title": "", * "collapsable": true, * "sidebarDepth": 2, * "children": ["/view/"] * }, * { * "title": "GFW", * "collapsable": true, * "sidebarDepth": 2, * "children": ["/view/GFW/"] * }, * { * "title": "html", * "collapsable": true, * "sidebarDepth": 2, * "children": [ * ["/view/html/day1", "day1"], * ["/view/html/day2", "day2"], * ["/view/html/day3", "day3"], * ["/view/html/day4", "day4"], * ["/view/html/day5", "day5"] * ] * }] */
    genSideBarGroup: (RootPath, unDirIncludes, SuffixIncludes, { title = ' ', children = [' '], collapsable = true, sidebarDepth = 2 }) = > {
        // Prepare to receive
        let sidebars = []
        let allDirs = filehelper.getAllDirs(RootPath, unDirIncludes)
        allDirs.forEach((item) = > {
            let children = filehelper.getAllFiles(item, unDirIncludes, SuffixIncludes)
            let dirname = item.replace(RootPath, "")
            let titleTemp = item.replace(RootPath + '\\view'."")
            title = titleTemp.replace(/\\/g.' ')
            if (children.length > 1) {
                children = children.flatMap((vo, idx) = > [[dirname.replace(/\\/g.'/') + vo, vo]])
            }
            let Obj = {
                title,
                collapsable: true.sidebarDepth: 2.children: children.length > 1 ? children : [dirname.replace(/\\/g.'/')]
            }
            sidebars.push(Obj)
        })
        return sidebars
    }
}

module.exports = { str, filehelper, sideBarTool }
Copy the code

config.js

    // Import the tool class that generated the sidebar
const { sideBarTool } = require(path.join(__dirname, './utils/index.js'))

// Some directories to exclude
let unDirIncludes = ['node_modules'.'assets'.'public'.'Network Engineering']
// Only file types with suffixes need to be handled
let SuffixIncludes = ['md'.'html']
    // Use the method generation sidebar
/ / the sidebar
let sidebar = sideBarTool.genSideBarGroup(rootPath, unDirIncludes, SuffixIncludes, {})
Copy the code

How to use

automation

If you’re like me, file directory is very much, want to group all the sidebar, support the fold open, then use sideBarTool. GenSideBarGroup ()

This method returns an array of organized sidebar objects, as shown below (configuration items on VuePress website)

If you want to have an automated sidebar without grouping, you can use sidebartool.gensidebar (), which returns an object, as shown below.

[This configuration requires that your directory structure be consistent]

If you’re not sure or confused, I suggest you read the official documentation first

Sidebar configuration

manual

Of course, I know that some students prefer to collapsable manually, for example when grouping, they want to set the collapsable parameter to false, or the sidebarDepth parameter to 1,3, etc. You can modify the source code provided above to do so. Either searching for gold, or waiting for me to update (lazy, probably not update)

The idea is very simple, iterate out the file directory, generate an object or array, the corresponding code has been in the article, you can study under their own

conclusion

The three steps

  • Create an index.js file (you can change it to whatever name you want, in any path you want, as long as you can find it)

Copy all the utils/index.js content of this article and paste it into the index.js you created.

  • In the config. Js import

In order to prevent some people do not understand, mian for his wife difficult to stick a picture

  • Use the method to get the generated data and assign it to the specified location