DEV Community

hichem ben chaabene
hichem ben chaabene

Posted on

Automatically register and load vue routes ๐Ÿ”ฅ (vue 2-3)

in the routes folder you can create a route loader file to automatically load routes then add them to the route registration of the app

// routeLoader.[js,ts]
import { RouteConfig } from 'vue-router';

export default function loadRoutes(): RouteConfig[] {
  const routes: RouteConfig[] = [];
  const requireRoutes = require.context(
    './routes',
    true,
    /^(?!.*test).*\.(js|ts)$/is,
  );

  requireRoutes.keys().forEach((fileName) => {
    const module = requireRoutes(fileName);
    const route = module.default || module;

    routes.push({
      ...(route as RouteConfig),
    });
  });

  return routes;
}
Enter fullscreen mode Exit fullscreen mode

In the route registration, assign loadRoutes to routes,
this will also work for nested routes

// routes/index.[ts|js]

import Vue from 'vue';
import VueRouter from 'vue-router';
import loadRoutes from './routeLoader';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: loadRoutes(),
});

export default router;
Enter fullscreen mode Exit fullscreen mode

Single route definition

import Home from '@/views/Home.vue';
import About from '@/views/About.vue';

// Nested route definition
import NestedRoutes from './nestedRoutes';

const routes: RouteConfig[] = [
  {
    path: '/',
    component: Home,
  },
  {
    path: '/about',
    component: About,
    children: NestedRoutes,
  },
];

export default routes;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)