Dynamically load Vue routes from different directories

Mohammad Alavi
2 min readMay 2, 2021

Sometime ago I was trying to come up with a scalable folder structure for my Vue app and I had to solve a problem with loading routes from different route files in different directories.

Normally we will define all our routes in a single route file like this:

const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
// and so on...
]
const router = new VueRouter({
routes // short for `routes: routes`
})

This may be fine for small projects but when the project grows, our route file will continue to grow and soon we will have a single route file which is very large and hard to manage.

Let’s say this is our project folder structure:

/src
/modules
/auth
/dashboard
/components
/pages
/routes
index.js
/store
/home
/profile
/...

Now let’s look at the contents of src/modules/dashboard/routes/index.js:

export default [
{
path: '/dashboard',
name: 'dashboard',
component: DashboardPage,
}
]

Here we define only the routes related to dashboard feature. But the question is how can we register them so our app will recognize them?

We can dynamically register them with the router:

Let me explain the following code section in loadRoutes() function:

require.context(‘@/modules’, true, /routes/index.js$/i)

Here require.context() returns a context module, which exports a keys function that returns an array of all possible requests (i.e., the matching paths), each of which could be passed to the context itself (which invokes its resolve function) to import the corresponding module. The returned array from loadRoutes() function looks like this:

resourceRoutes = [
{
0: [
{
path: '/dashboard',
name: 'dashboard',
component: {
name: 'DashboardPage',
...
}
]
},
{
1: [
...
]
},
{
2: [
...
]
},
...
]

So we just loop through each returned item, get the first array item, and add it to the routes array.

With this approach we will have a modular and scalable application.

Follow me on Twitter Mohammad Alavi

--

--

Mohammad Alavi

Full stack web developer — Looking for remote job opportunities