前言
最近在工作中发现项目开始用require.context来管理项目的模块结构了,比较好奇require.context到底是什么,有什么作用。
作用
通过正则遍历文件夹获取文件的上下文,可以很方便的帮助项目批量(自动)导入相关配置。
用法
require.context接收三个参数:开始的目录路径,是否遍历子目录,正则
返回一个函数包含三个参数:resolve,keys,id
The exported function has 3 properties:
resolve,keys,id.
resolveis a function and returns the module id of the parsed request.keysis a function that returns an array of all possible requests that the context module can handle.idis the module id of the context module. This may be useful formodule.hot.accept.
// require.context(directory, useSubdirectories = true, regExp = /^\.\/.*$/, mode = 'sync');
files = require.context('./test', false, /\.test\.js$/);
files.keys()返回文件名数组
let exampleFile = files.keys()[0];
fiels[exampleFile]; // exampleFile文件上下文 -- 可以理解成import过来的对象
Example
针对Vue路由配置进行优化。https://juejin.im/post/5c106485e51d450e657571a6
参考链接
https://www.jianshu.com/p/c894ea00dfec
官方文档:https://webpack.js.org/guides/dependency-management/
本文探讨了require.context在项目模块管理中的作用,详细解释了其如何通过正则表达式遍历文件夹,实现自动导入配置文件。适用于优化如Vue路由等复杂配置场景。
1513

被折叠的 条评论
为什么被折叠?



