1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- const fs = require('fs')
- const path = require('path')
- // 将文件路径截取为路由路径
- function slicePathToRoute(filePath) {
- return filePath
- .slice(0, filePath.length - 4)
- .replace(path.join(__dirname, 'pages'), '')
- }
- function generateDirToRoutes(filename) {
- const routes = []
- // 读取文件夹
- function readDir(last, next) {
- const entry = path.join(last, next)
- const stat = fs.statSync(entry)
- // 如果是文件夹
- if (stat.isDirectory()) {
- const dirList = fs.readdirSync(entry)
- dirList.forEach((dir) => {
- readDir(entry, dir)
- })
- } else {
- // 文件 直接打印
- routes.push(slicePathToRoute(entry))
- }
- }
- readDir(__dirname, filename)
- return routes
- }
- function generateRoutes(list, name, root = 'pages') {
- const reslut = []
- const routes = generateDirToRoutes(path.join(root, name))
- console.log(routes)
- list.forEach((item) => {
- routes.forEach((route) => {
- const res = route.replace(`\\${name}\\`, '')
- if (res.startsWith(item.type)) {
- const a = route.replace(name, item.id).replaceAll('\\', '/')
- console.log(a)
- reslut.push(a)
- }
- })
- })
- return reslut
- }
- // const list = [{ id: 102, type: 'ldm' }]
- // const routes = generateRoutes(list, '_template')
- // console.log(routes)
- export default generateRoutes
|