[Vuejs]-Autoload routes as modules

0๐Ÿ‘

โœ…

I had to set const routes = []; and had to .push() it to the array.

So the following code works:

index.js

const requireRoute = require.context('.', false, /\.js$/); // extract js files inside modules folder
const routes = [];

requireRoute.keys().forEach((fileName) => {
  if (fileName === './index.js') return; // reject the index.js file

  routes.push(requireRoute(fileName).default);
});

export default routes;

router.js

import Vue from 'vue';
import Router from 'vue-router';

import routes from '@/routes/modules';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

0๐Ÿ‘

Try to spread your routes object, so your main routes will contain not a single object, but a bunch of objects:

routes: [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      icon: 'fa-tachometer',
      title: 'Dashboard',
      inMenu: true,
    },
  },
  ...routes,
],

Leave a comment