从 Vue 的生产构建中删除选定的路由

Ond*_*čík 2 javascript build webpack vue.js

有没有办法从 Vue 应用程序的生产版本中删除一些带有链接组件的路由?

在我的应用程序中,我有只有我使用的管理器界面,因此不需要在生产版本中包含它的逻辑。我想避免在生产构建中实际使用任何管理器代码,因为我只能在本地主机上的开发过程中使用管理器页面。

这是我现在拥有的简单示例。managerCheck 测试用户是否是管理员,以允许用户进入或将其重定向回主页。这可能就足够了,因为它还与 MongoDB 中的检查相结合,但我仍然希望不将管理器的组件逻辑包含在生产构建中,因为 ManagerView 包含非常强大的功能,并且安全总比后悔好。

// 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
    }
})
Run Code Online (Sandbox Code Playgroud)

Naf*_*dır 7

在生产中,可以过滤掉不必要的路由。

可以使用 ProductionAvailable 标志定义路由。

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,
    }
}]
Run Code Online (Sandbox Code Playgroud)

如果节点环境设置为 ,则在导出时对其进行过滤production

export default new Router({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes: process.env.NODE_ENV === 'production' ? routes.filter((route) => route.productionAvailable) : routes,
})
Run Code Online (Sandbox Code Playgroud)

  • 也是很棒而简单的解决方案,感谢您的宝贵时间。 (3认同)