一、什么是 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.
– webpack 官方说明
二、如何使用
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);
// 示例
require.context('./test', false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request ending with `.test.js`.
| 参数 | 类型 | 说明 |
|---|---|---|
| dirname | String | 需要读取模块的文件的所在目录 |
| useSubdirectories | Boolean | 是否遍历子目录 |
| RegExp | RegExp | 匹配的规则(正则表达式) |
导出的函数有 3 个属性: resolve, keys, id.如下表所示
| 属性 | 类型 | 说明 |
|---|---|---|
| resolve | Function | 接受一个参数request,request为文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径 |
| keys | Function | 返回一个数组,由匹配成功的文件所组成的数组 |
| id | String | 执行环境的 id |
function importAll(r) {
r.keys().forEach(r);
}
importAll(require.context('../components/', true, /\.js$/));