Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

christopher's avatar

Vue 2 - Swap out routes to a separate File

Currently i am building a Vue2 APP and i am wondering how i can swap out my routes to a separate File. So this is a bit of my bootstrap.js

const routes = [
    {
        path: '/hosting',
        component: require('./components/support/index.vue'),
    },
    .....
    .....
]

const router = new VueRouter({
    routes // short for routes: routes
})

const App = Vue.extend(require('./backend.vue'))

const app = new Vue({
    router,
    render: h => h(App),
}).$mount('#app')

If i make a separate File with the Routes, for example a routes.js with its content

const routes = [
    {
        path: '/hosting',
        component: require('./components/support/index.vue'),
    },
    .....
    .....
]

How would i swap out this to a separate file? I tried it like so bootstrap.js

import routes from './routes'
...
Vue.use(VueRouter);

const router = new VueRouter({
    routes 
})
...

And my routes.js file

module.exports = {

    routes: function () {

        routes = [
            {
                path: '/support',
                component: require('./components/support/index.vue'),
            },
        ]

    }
}

But i am just getting the error message Uncaught TypeError: routes.forEach is not a function . Can someone give a little tip? :)

0 likes
6 replies
eminiarts's avatar

I get the same error and am trying to find a solution... will let you know if I find anything.

Any help from others?

andreiculda's avatar

@prasinoulhs you are right:

module.exports = [
    {
        path: '/',
        component: require('../components/Home/home.vue'),
            meta: {
                    title: 'Home'
        }
]

This works in routes.js file exports, where you can even require more components.

daisyHawen's avatar

I have the same error, maybe you need to return an array in config.js

kunaldodiya's avatar

users.js

module.export = [ { path: '/', component: 'Home' } ];

pages.js

module.export = [ { path: '/about', component: 'About' } ];

router.js

var usersRoute = require('./routes/users'); var pagesRoute = require('./routes/pages');

var routeLists = []; var routes = routeLists.concat(usersRoute, pagesRoute);

export default new VueRouter({ routes, linkActiveClass: "is-active", mode: "history" });

Please or to participate in this conversation.