Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

路由去中心化 #8

Open
fengyua5 opened this issue Jul 26, 2018 · 0 comments
Open

路由去中心化 #8

fengyua5 opened this issue Jul 26, 2018 · 0 comments

Comments

@fengyua5
Copy link
Owner

fengyua5 commented Jul 26, 2018

路由去中心化

随着前端业务的越来越复杂,SPA(Signal Page Application)单页面应用越来越流行,我们一般用三大
框架(Angular、Vue、React)居多,我们一般用react-router、vue-router做单页面的路由跳转,不知道
大家有没有遇见类似的配置

   let routers = [
     {component: App, path: '/'..},
     {component: Account, path: '/account'..},
     {component: User, path: '/user'..},
     ...
   ]

当我们的路由url配置很多的时候,我们维护越来越困难,有以下几方面原因

  • 多人维护时两个同时修改这个routers文件,在git上就会冲突(这个问题可解决)
  • 文件配置太多,我们找一个url会查询很久
  • 我们添加一个文件都要修改routers文件,觉得很麻烦
  • 不够模块化和工程化

解决办法

1、模块化管理

当我们工程越来越大后,根据分治思想我们一般会分块维护,比如目录如下

---app
------router.js
------account
---------index.js
---------router.js
------user
---------index.js
---------router.js

采取这种方式的话,我们会把User模块的路由放在user/router.js文件中,模块的分层特别明显,我们要
找/user开头的路由直接去user目录下去找,清晰明了,但是又有人要问,我们每次添加一个模块,我们 都要引入这个js文件能不能自动引入啊,答案是可以

2、路由去中心化

我们都知道node引入文件一般是用require这个api,还有一个大家不经常用的api
require.context这个函数,

module.exports = {
  path: '/',
  title: 'aa',
  component: require('./App'),
  childRoutes: (r => {
    return r.keys().reduce((pre, cur) => {
      return pre.concat(r(cur));
    }, []);
  })(require.context('./', true, /^\.\/((?!\/)[\s\S])+\/router\.js/))
};

我们可以通过一定的工程化自动引入各个router.js文件,这样的有点

  • 分模块维护
  • 自动化引入,再也不用手动引入这个文件了

最后

我们也可以用于引进其他文件,比如说action、reducers等等
链接 require.context api
如果觉得还不错,请给一个star

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant