Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 根据目录自动生成路由 #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# homework14
# autorouter

基于vue3 简单实现一个根据文件结构自动生成路由的vite插件

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

117 changes: 116 additions & 1 deletion src/directory-parser.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,132 @@
const fs = require('fs')
const path = require('path')

// `{ name: 'level1-about', path: '/level1/about', component: () => import('/${dir}/level1/about.vue') }`,
const template = `{ name: '{0}', path: '{1}', component: () => import('/{2}') }`
const templateWithChildren = `{ path: '{1}', component: () => import('/{2}'), children: [ {3} ] }`

function parsePagesDirectory(
dir,
{ prependName, prependPath } = { prependName: '', prependPath: '/' },
) {
let routes = []

//TODO
const files = dfsFiles(dir, dir, '.vue')
for (let f of files) {
if (!f.children) {
routes.push(
template.replace('{0}', f.name).replace('{1}', f.path).replace('{2}', f.currentFilePath)
)
} else {
routes.push(
templateWithChildren.replace('{1}', f.path)
.replace('{2}', f.currentFilePath)
.replace('{3}', parse(f.children))
)
}

}

return { routes }
}


function parse(children) {
let r = []

for (let child of children) {
if (!child.children) {
r.push(
template.replace('{0}', child.name).replace('{1}', child.path).replace('{2}', child.currentFilePath)
)
} else {
routes.push(
templateWithChildren.replace('{1}', child.path)
.replace('{2}', child.currentFilePath)
.replace('{3}', parse(child.children))
)
}
}
return r.join(', ')
}

// 遍历目录,把目录中带suffix后缀, 并且英文字母开头的文件路径返回
function dfsFiles(filePath, baseDir, suffix, isChildren = false) {
let allFilePaths = []
if (!fs.existsSync(filePath)) {
throw new Error(`filepath: ${filePath} not exist`)
}

const files = fs.readdirSync(filePath)
files.sort((f1, f2) => {
if ((f1.endsWith(suffix) && (f2.endsWith(suffix))) ||
(!f1.endsWith(suffix) && (!f2.endsWith(suffix)))) {
if (f1.startsWith('_') && !(f2.startsWith('_'))) {
return -1
} else if(!f1.startsWith('_') && (f2.startsWith('_'))) {
return 1
} else {
return 0
}
} else if (f1.endsWith(suffix)) {
return -1
} else {
return 1
}
})
for (let file of files) {
let currentFilePath = filePath + '/' + file
let stats = fs.lstatSync(currentFilePath)
if (stats.isDirectory()) {
let name = currentFilePath.replace(baseDir, '').slice(1).replace(/\//g, '-')
if (name.includes('_')) {
name = name.replace(/_/g, '')
}
// console.log('n', name, allFilePaths, currentFilePath)
let t = allFilePaths.findIndex(f => f.name === name)
if (t !== -1) {
let ft = {path: allFilePaths[t].path, currentFilePath: allFilePaths[t].currentFilePath}
ft.children = dfsFiles(currentFilePath, baseDir, suffix, true)
allFilePaths[t] = ft
// console.log('f', allFilePaths)
continue
}
allFilePaths = allFilePaths.concat(dfsFiles(currentFilePath, baseDir, suffix, false))
} else {
if (file.endsWith(suffix) && /^[_A-Za-z]+/.test(file) ) {
let path
if (!isChildren) {
path = currentFilePath.replace(baseDir, '').replace(suffix, '')
} else {
path = file.replace(suffix, '')
}
if (path.endsWith('index')) {
path = path.slice(0, path.length - 5)
}
if (path.includes('_')) {
path = path.replace(/_/g, ':')
}

let name = currentFilePath.replace(baseDir, '').replace(suffix, '').slice(1).replace(/\//g, '-')
if (name.endsWith('-index')) {
name = name.slice(0, name.length - 6)
}
if (name.includes('_')) {
name = name.replace(/_/g, '')
}

allFilePaths.push({name: name,
path: path,
currentFilePath
})
}
}
}

return allFilePaths
}


module.exports = {
parsePagesDirectory,
}
1 change: 0 additions & 1 deletion tests/directory-parser.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ test('directory with everything', () => {
}`,
`{ name: 'about', path: '/about', component: () => import('/${dir}/about.vue') }`,
oneLine`{
name: 'contact',
path: '/contact',
component: () => import('/${dir}/contact.vue'),
children: [
Expand Down