什么是webpack的require.context?前端
官网解释:react
您可使用require.context()函数建立本身的上下文。webpack
它容许您传入一个目录进行搜索,一个标志表示是否也应该搜索子目录,以及一个正则表达式来匹配文件。git
在构建时,webpack解析代码中的require.context()。github
直接在项目中使用,个人webpack4+react的一个开源项目,很早以前写的移动端项目,你们有兴趣能够看看,给个Star。web
gitHub地址:https://github.com/JinJieTan/react-webpack
而且这个项目仍是带docker+gitHub+Travis CI的,教程在我以前写的这里:正则表达式
前端工程师学Docker ? 看这篇就够了 【零基础入门;原创】 docker
项目结构:express
+ src + APP.jsx + pages + buy + index.jsx + home + index.jsx + person + index.jsx //... + index.js //....
我在src文件夹下的APP.jsx中使用webpack的require.context API数组
require.context('./pages', true, /\.jsx$/)
require.context接受三个参数,官网解释:
It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.
意思是:
它容许你经过一个目录进行搜索,flag指定是否搜索子目录,以及与文件匹配的正则表达式
也就是说 require.context 有三个参数:
当我使用
require.context('./pages', true, /\.jsx$/)
获得的打印返回值是:
ƒ webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } ,"测试"
官网解释:
上下文模块导出一个(require)函数,该函数接受一个参数:请求。 导出的函数有3个属性:解析、键值、id。 resolve是一个函数,返回解析后的请求的模块id。 keys是一个函数,它返回上下文模块能够处理的全部可能请求的数组。
我按照官网示例演示,加入新的代码:
const cache = {}; function importAll (r) { r.keys().forEach(key => cache[key] = r(key)); } importAll(require.context('./pages', true, /\.jsx$/)); console.log(cache,'cache')
我获得一些模块信息:
你们可能会联想到路由结合的使用,放一个示例代码,以前咱们在react中写声明式路由,集中化管理须要这样:
// rootRoute.js const rootRoute = { childRoutes: [ { path: '/', component: AppLayout, childRoutes: [ require('./modules/shop/route'), //购买详情页 require('./modules/order/route'), // 订单页 require('./modules/login/route'), // 登陆注册页 require('./modules/service/route'), // 服务中心 // ... // 其余大量新增路由 // ... ] } ] };
如今咱们只须要这样,就能够实现去中心化路由管理
const rootRoute = { childRoutes: [ { path: '/', component: AppLayout, childRoutes: (r => { return r.keys().map(key => r(key)); })(require.context('./', true, /^\.\/modules\/((?!\/)[\s\S])+\/route\.js$/)) } ] };
这里childRoutes是一个IIFE,马上能够执行函数,传入require.context的结果,r就是初始值
修改以前的代码成这样:
const childRoutes = ((r) => { console.log(r.keys(), 'keys'); return r.keys().map((key) => { console.log(key,'key',r(key)) return r(key); }); })(require.context('./pages', true, /\.jsx$/)); console.log(childRoutes, 'childRoutes');
看打印结果
这样每一个childRoutes的子节点,就是个require进来的模块啦
优化后,新增一个业务模块,只要业务模块 route 文件遵循统一的目录结构。业务模块 route 就能被自动关联到 rootRoute 里。
若是感受写得不错,记得点个赞,关注下:前端巅峰专栏和个人公众号