@egoist/routes-generator
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

@egoist/routes-generator

NPM version NPM downloads CircleCI donate chat

Generate routes from filesystem, use case: Next/Nuxt-style routing

Install

yarn add @egoist/routes-generator

Usage

The kitchen sink example, generate routes array from files:

const { toRoutes } = require('@egoist/routes-generator')

const files = [
  '[user].vue',
  '[user]/index.vue',
  '[user]/profile.vue',
  'index.vue'
]
const expectedRoutes = [
  {
    path: '/',
    file: '/my-app/index.vue',
    name: 'index-vue'
  },
  {
    path: '/:user',
    file: '/my-app/[user].vue',
    name: '-user--vue',
    children: [
      {
        path: '',
        file: '/my-app/[user]/index.vue',
        name: '-user--index-vue'
      },
      {
        path: 'profile',
        file: '/my-app/[user]/profile.vue',
        name: '-user--profile-vue'
      }
    ]
  }
]

assert.deepEqual(
  toRoutes(files, {
    cwd: '/my-app'
  }),
  expectedRoutes
)

Nesting Routes

When both a file and a directory with the same name as the file exist, the files in the directory will be used as child routes:

In:

user.vue
user/index.vue
user/profile.vue

Out:

{
  path: '/user',
  file: 'user.vue',
  children: [
    {
      path: '',
      file: 'user/index.vue'
    },
    {
      path: 'profile',
      file: 'user/profile.vue'
    }
  ]
}

Use with fast-glob and chokidar:

yarn add fast-glob chokidar
const { toRoutes } = require('@egoist/routes-generator')
const glob = require('fast-glob')
const chokidar = require('chokidar')

const patterns = ['**/*.vue']
const cwd = './src/routes'

const files = new Set(glob.sync(patterns, { cwd }))
let routes = toRoutes(files, { cwd })

const watcher = chokidar.watch(patterns, { cwd, ignoreInitial: true })
watcher.on('add', file => {
  files.add(file)
  routes = toRoutes(files, { cwd })
})
watcher.on('unlink', file => {
  files.delete(file)
  routes = toRoutes(files, { cwd })
})

API

toRoutes(files, options)

  • Params:
    • files: Set<string> | Array<string>
    • options={}:
      • cwd='': string

Convert an array (or set) of files to routes.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

Author

@egoist/routes-generator © EGOIST, Released under the MIT License.
Authored and maintained by EGOIST with help from contributors (list).

egoist.sh · GitHub @EGOIST · Twitter @_egoistlily

Readme

Keywords

none

Package Sidebar

Install

npm i @egoist/routes-generator

Weekly Downloads

3

Version

1.0.6

License

MIT

Unpacked Size

9.73 kB

Total Files

6

Last publish

Collaborators

  • egoist