preface

If you have any problems at work, doubts in the interview, or obstacles in the front end, you can join our front End Youdao Family. I will try my best to answer your questions and solve your doubts, so that we can work together and grow together.

Click to add technical exchange group or follow the public account 🎨 front youdao

Mainly is to configure the sidebar is too trival, file or directory structure adjustment file modification, need to modify the file path, is the trouble is that I don’t want to spend too much time in it, after all have time on a whim think in a certain directory is more appropriate, you replace the global path, might not pay attention to modify the wrong, uploaded to the server, and a wave, Ha ha listen to you seriously say, is too lazy, nonsense what big truth, ha ha.

Usage

Generally, article directories are divided into two types, single directory structure, and multi-directory structure. Below is a brief description of how to use tool functions to generate directories.

Interested students, but do not want to manual configuration file cumbersome, you can run the configured project, run or debug learning. Click to jump to GitHub warehouse, don’t know where you can ask me in the group

Single-directory structure, as shown

Configure the sidebar 在config.jsIn the configurationsidebarproject

The effect

tips

  • Remember to pay attention to the case of the file name, do not ask why, was cheated
  • Tool function and article path remember corresponding, otherwise will report an error

If you keep getting errors or looking at the generated data directory, you can turn on debug mode and add –debug by running the command suffix in package.josn

inconsole.log(vue), you can view the printed data in the terminal, as shown in the figure

More catalog

Configure the sidebar

The effect is shown in figure

The article sorted

I am a person with pursuit, make the data catalog according to the order I want to sort, otherwise the creation of catalog will affect the beauty of my blog, obsessive-compulsive patients, yeah arrangement.

When I write more than 10 articles, I find that 10.CSS. Md is ranked after 01. Check the data and find that the files read are not sorted according to the directory order. Solve the problem if you find this problem.

Sort the data, and finally the order is correct, very good.

The file specification can be defined with this name, and can be adjusted more flexibly later.

  • Folders are available10,20,30At the beginning of the order, if you want to be at the end10 ~ 20Insert a new directory between, so as long as write11, 12Line,
  • The file can be named in this way, if you consider that there are more than 100 subsequent files, you can use it100,200,300Start, which allows you to insert more files in the middle without having to re-edit the following file names.

Insight into the

First we know what kind of data structure we want.

directory

We want to get the following data.

  sidebar: {
    '/frontend/': [
      ' '.// README can be used without a file name
      {
        title: 'HTML'.collapsable: false.children: [['HTML/HTML Quick Start '.'HTML Quick Start '],
          ['HTML/HTML Basics'.'HTML Basics']],}, {title: 'CSS'.collapsable: false.children: [['CSS / 01. CSS based'.'the CSS based'],
          ['CSS / 02. CSS beautification'.'CSS beautification'[,],},],},Copy the code

So of course we go through Nodefs.readdirSyncAPI to read the file, get an array, the array of data in the figure below

We can split each string into an array and get [“Vue Popover component development “,” MD “]. Since we don’t want to show the file in the directory, we can reset it with [file path, file name] format. [‘README’, ‘README’] : [‘README’, ‘README’]

[
  {
    title: 'Vue.js',
    collapsable: false,
    children: [
      '',      
      [Array], [Array]
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array] 
    ]
  }
]
Copy the code

If we want to contain multiple subfolders through a parent folder, obviously the above method does not apply to this situation, we should get data a folder a category, such as the following data

[
  {
    title: 'Vue.js',
    collapsable: false,
    children: [
      '',      
      [Array], [Array]
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array] 
    ]
  },
  {
    title: 'Vue3.js',
    collapsable: false,
    children: [
      '',      
      [Array], [Array]
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array], [Array],
      [Array] 
    ]
  }
]
Copy the code

So when the file we read through stat.isdirectory () is a folder, we define an object in which the children property is an empty array, and recursively re-call the method to push the read file into the children array. Ha, ha. Done.

const fs = require('fs') // File module
const path = require('path') // Path module
const docsRoot = path.join(__dirname, '.. '.'.. '.'.. ') // docs file path
const chalk = require('chalk') // Command line print beautification
const log = console.log

function ReadFile(dir = docsRoot, filesList = [], fpath = ' ') {
  let files = fs.readdirSync(dir)
  // 10 1 sort error
  if(Array.isArray(files)){
    files.sort((item1, item2) = > {
      let c1 = item1.split('. ') [0]
      let c2 = item2.split('. ') [0]
      return c1 - c2
    })
  }
  console.log('-- -- -- -- -- -);
  console.log(files);
  files.forEach((item, index) = > {
    let filePath = path.join(dir, item)
    const stat = fs.statSync(filePath)
    // log('isDirectory-------------------', stat.isDirectory(), item)
    Md dir:/Users/xx/reg-rules-js-site/docs/regular
    const fileNameArr = path.basename(filePath).split('. ')
    if(stat.isDirectory() && item ! = ='.vuepress') {
      // Generate the directory name
      let title = fileNameArr.length > 1 ? fileNameArr[1] : fileNameArr[0]
      if(! title){ log(chalk.yellow('Warning: This folder'${filePath}"If the name is not named according to the convention, the generated data will be ignored. `))
        return
      }
      filesList.push({
        title,
        collapsable: false.children: [],})// log(' filesList[index].children ', path.join(dir, item), filesList[index].children, item)
      / / read recursive folder files/Users/another/Documents/self - study/reg - rules - js - site/docs/test/test2 [] test2
      ReadFile(path.join(dir, item), filesList[index].children, item)
    } else {
      // Generate an array of file names
      let name = null
      title = null
      typeFile = null
      pathName = null
      let cloneArr = [...fileNameArr]
      typeFile = cloneArr[cloneArr.length - 1]
      if (fileNameArr.length > 1) {
        cloneArr.pop()
        name = cloneArr.join('. ')
        pathName = fpath ? `${fpath}/${name}` : name
        title = cloneArr.length > 1 ? cloneArr[1] : cloneArr[0]}else {
        log(chalk.yellow('Warning: This file'${filePath}"If the name is not named according to the convention, the generated data will be ignored. `))
        return
      }

      log('name', name, pathName, typeFile, title)
      if(name === 'README'){
        
      }
      // Filter non-MD files
      if (typeFile === 'md') {
        if(name === 'README') return filesList.unshift(' ')
        filesList.push([pathName, title])
      }
    }
  })
  return filesList
}

module.exports = ReadFile
Copy the code

Started originally is a simple function, used to handle a single directory structure, thinking behind the single directory if the number of cases, nav certainly does not put down, or certainly not good-looking, solve the catalog file, after online, some file name length is different, more see more think torque, then rewrite, architecture new data format, well, now look good.