generate.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const fs = require('fs')
  2. const path = require('path')
  3. // 将文件路径截取为路由路径
  4. function slicePathToRoute(filePath) {
  5. return filePath
  6. .slice(0, filePath.length - 4)
  7. .replace(path.join(__dirname, 'pages'), '')
  8. }
  9. function generateDirToRoutes(filename) {
  10. const routes = []
  11. // 读取文件夹
  12. function readDir(last, next) {
  13. const entry = path.join(last, next)
  14. const stat = fs.statSync(entry)
  15. // 如果是文件夹
  16. if (stat.isDirectory()) {
  17. const dirList = fs.readdirSync(entry)
  18. dirList.forEach((dir) => {
  19. readDir(entry, dir)
  20. })
  21. } else {
  22. // 文件 直接打印
  23. routes.push(slicePathToRoute(entry))
  24. }
  25. }
  26. readDir(__dirname, filename)
  27. return routes
  28. }
  29. function generateRoutes(list, name, root = 'pages') {
  30. const reslut = []
  31. const routes = generateDirToRoutes(path.join(root, name))
  32. console.log(routes)
  33. list.forEach((item) => {
  34. routes.forEach((route) => {
  35. const res = route.replace(`\\${name}\\`, '')
  36. if (res.startsWith(item.type)) {
  37. reslut.push(route.replace(name, item.id))
  38. }
  39. })
  40. })
  41. return reslut
  42. }
  43. const list = [{ id: 102, type: 'ldm' }]
  44. const routes = generateRoutes(list, '_template')
  45. console.log(routes)