Automatic route generation for Vue

Jelle Hak
1 min readApr 8, 2020

The Nuxt framework has a particular interesting feature called automatic routing. The goal is to have this feature in a regular Vue app. After some internet searching I quickly stumbled on https://github.com/ktsn/vue-auto-routing and the great tutorial from Michal https://codeburst.io/automatic-routing-in-vue-js-applications-1403ba425bfa. I tried to implement this plugin but it felt it could be done a bit easier. Luckily webpack has the ability to do some runtime magic with the use of require.context.

How it works

1. Add the followingregister.js script to a folder for example ./pages https://gist.github.com/jellehak/9bc42d5e14e75091c5526594560c2aa1

2. Include the automaticly generated routes like in the following script. You can also add here or prepend your regular routes.

import routes from './pages/register';

export default new Router({
routes: [
...routes
// {
// path: '*',
// component: PageNotFound
// }
]
})

This will turn a folder structure like this:

pages
|- dashboard
|- photos
|- users
| |- index.vue
| |- _id.vue

into a proper VueRouter object.

Full code and readme can be found here: https://gist.github.com/jellehak/9bc42d5e14e75091c5526594560c2aa1

--

--