Reputation: 1599
Is there a way to remove some routes with their linked components from production build of Vue app?
In my app I have manager interface that only I use so there is no need to have it's logic in the production build. I want to avoid having any of manager's code actually used in the production build as I can use the manager page only during development on localhost.
Here is simple example what I have now. The managerCheck tests if user is manager to allow user to enter or to redirect him back to the homepage. This is probably enough as it is also combined with check in MongoDB but I still would love to not includes manager's components logic inside production build as ManagerView includes pretty powerful functions and it is better to be safe than sorry.
// router.js
// ... some imports
const userCheck = (to, from, next) => store.getters['user/user'] ? next() : next({path: '/login'})
const managerCheck = (to, from, next) => store.getters['user/manager'] ? next() : next({path: '/'})
export default new Router({
mode: 'hash',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'App Name',
component: MainView,
},
{
path: '/user',
name: 'User',
component: UserView,
beforeEnter: userCheck
},
{
path: '/manager',
name: 'Manager',
component: ManagerView,
beforeEnter: managerCheck
}
})
Upvotes: 2
Views: 1726
Reputation: 8329
I would do something like this:
// router.js
// ... some imports
const userCheck = (to, from, next) => store.getters['user/user'] ? next() : next({path: '/login'})
const managerCheck = (to, from, next) => store.getters['user/manager'] ? next() : next({path: '/'})
const clientRoutes = [
{
path: '/',
name: 'App Name',
component: MainView,
},
{
path: '/user',
name: 'User',
component: UserView,
beforeEnter: userCheck
}
]
const managerRoutes = []
// you may have to look into process.env to set this condition correctly
if (process.env.NODE_ENV !== 'production') {
managerRoutes.push({
path: '/manager',
name: 'Manager',
component: ManagerView,
beforeEnter: managerCheck
})
}
export default new Router({
mode: 'hash',
base: process.env.BASE_URL,
routes: [...clientRoutes, ...managerRoutes]
})
process.env: https://cli.vuejs.org/guide/mode-and-env.html#modes
Upvotes: 2
Reputation: 495
In production, unnecessary routes can be filtered out.
Routes can be defined with productionAvailable flag.
routes: [
{
path: '/',
name: 'App Name',
component: MainView,
productionAvailable: true,
},
{
path: '/user',
name: 'User',
component: UserView,
beforeEnter: userCheck,
productionAvailable: true,
},
{
path: '/manager',
name: 'Manager',
component: ManagerView,
beforeEnter: managerCheck,
productionAvailable: false,
}
}]
Then filter it when exporting if the node env is set to production
.
export default new Router({
mode: 'hash',
base: process.env.BASE_URL,
routes: process.env.NODE_ENV === 'production' ? routes.filter((route) => route.productionAvailable) : routes,
})
Upvotes: 7