I am creating a Vue starter kit app for a platform, and it will use a standard directory structure for creating all of the items needed for a resource (.vue files, routes, Vuex store modules, etc). I would like to take advantage of this known structure to dynamically load router path objects so the user doesn't have to manually add routes to the router index file.
For example, here's a sample directory structure:
/src
|
---resources
|
-------user
|
---User.vue
---routes.js
---store.js
event
|
---Event.vue
---routes.js
---store.js
job
|
---Job.vue
---routes.js
---store.js
The inside of a routes.js file looks like this:
import Event from '@/resources/event/Event'
export default [
{
path: '/events',
name: 'event',
component: Event
},
];
To do this manually in a standard router file (router.js or router/index/js), you would do something like this:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Auth from '@/components/Auth';
import eventRoutes from '@/resources/event/routes.js';
import userRoutes from '@/resources/user/routes.js';
import jobRoutes from '@/resources/job/routes.js';
Vue.use(Router);
let baseRoutes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/login',
name: 'auth',
component: Auth
},
];
const routes = baseRoutes.concat(shiftCalendarRoutes)
.concat(eventRoutes)
.concat(userRoutes)
.concat(jobRoutes);
export default new Router({
mode: 'history',
routes,
})
What I would really like to do is this:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Auth from '@/components/Auth';
Vue.use(Router);
let routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/login',
name: 'auth',
component: Auth
},
];
function loadRoutes() {
const routes = require.context('@/resources', true, /routes.js$/i);
routes.keys().forEach((key) => {
const path = '@/resources/' + key.substring(2);
// Dynamically import file using import statement
import something from path;
// Add imported default object to routes object.
});
return routesList;
}
export default new Router({
mode: 'history',
routes,
})
The problem I'm running into is the actual import. When I try something like
routeItems.keys().forEach((key) => {
// routesList.push('@/resources/' + key.substring(2));
const path = '@/resources/' + key.substring(2);
const routeModule = import(path).default();
});
I get a Critical dependency: the request of a dependency is an expression webpack error. I've tried other versions of import without any luck.
Is it possible to do what I'm trying to do with dynamic importing?