天天看点

require.context是什么

前言

最近在工作中发现项目开始用require.context来管理项目的模块结构了,比较好奇require.context到底是什么,有什么作用。

作用

通过正则遍历文件夹获取文件的上下文,可以很方便的帮助项目批量(自动)导入相关配置。

用法

require.context接收三个参数:开始的目录路径,是否遍历子目录,正则

返回一个函数包含三个参数:resolve,keys,id

The exported function has 3 properties:

resolve

,

keys

,

id

.
  • resolve

    is a function and returns the module id of the parsed request.
  • keys

    is a function that returns an array of all possible requests that the context module can handle.
  • id

    is the module id of the context module. This may be useful for

    module.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/