generate.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. const a = route.replace(name, item.id).replaceAll('\\', '/')
  38. console.log(a)
  39. reslut.push(a)
  40. }
  41. })
  42. })
  43. return reslut
  44. }
  45. // const list = [{ id: 102, type: 'ldm' }]
  46. // const routes = generateRoutes(list, '_template')
  47. // console.log(routes)
  48. export default generateRoutes