使用 Node.js 自动创建 Vue 的路由

警告
本文最后更新于 2023-07-07,文中内容可能已过时。

最近在写一个 Vue 插件,需要在项目中创建一些测试页面,由于都是些静态路由,就想到之前看到过的一个项目就是用 Node.js 来自动生成路由的,于是就借鉴过来改了一下。

源码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const fs = require('fs')
const os = require('os')

const vueDir = './src/views/'
const routerFile = './src/router.js'

fs.readdir(vueDir, function (err, files) {
  if (err) {
    console.error('❌ Could not list the directory.', err)
    return
  }
  const routes = []
  for (const filename of files) {
    if (filename.indexOf('.') < 0) {
      continue
    }
    const [name, ext] = filename.split('.')
    if (ext !== 'vue') {
      continue
    }
    const routeName = name.replace(/-([a-z])/g, (_, match) => match.toUpperCase())
    let routeDescription = ''
    const contentFull = fs.readFileSync(`${vueDir}${filename}`, 'utf-8')
    // get route description from first line comment
    const match = /<!--\s*(.*)\s*-->/g.exec(contentFull.split(os.EOL)[0])
    if (match) {
      routeDescription = match[1].trim()
    }
    routes.push(`  {
    path: '/${name === 'home' ? '' : name}',
    name: '${routeName}',${routeDescription ? `\n    description: '${routeDescription}',` : ''}
    component: () => import(/* webpackChunkName: "${routeName}" */ '@/views/${filename}'),
  },`)
  }
  const result =
`// This file is automatically generated by gen-router.js, please do not modify it manually!
import VueRouter from 'vue-router'
import Vue from 'vue'

Vue.use(VueRouter)

const routes = [
${routes.join(os.EOL)}
]

const router = new VueRouter({
  mode: 'hash',
  routes,
})

export default router
`
  fs.writeFile(routerFile, result, 'utf-8', (err) => {
    if (err) throw err
    console.log(`✅ Router generated successfully in ${routerFile}`)
  })
})

生成效果如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// This file is automatically generated by gen-router.js, please do not modify it manually!
import VueRouter from 'vue-router'
import Vue from 'vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    description: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home.vue'),
  },
]

const router = new VueRouter({
  mode: 'hash',
  routes,
})

export default router

参考

sunzsh/vue-el-demo

Buy me a coffee~
支付宝
微信
0%