require.context是什么

一个webpack的api,通过执行require.context函数获取一个特定的上下文,主要用来实现自动化导入模块,在前端工程中,如果遇到从一个文件夹引入很多模块的情况,可以使用这个api,它会遍历文件夹中的指定文件,然后自动导入,使得不需要每次显式的调用import导入模块

 

require.context函数接受三个参数

  1. directory {String} -读取文件的路径

  2. useSubdirectories {Boolean} -是否遍历文件的子目录

  3. regExp {RegExp} -匹配文件的正则

require.context(directory, useSubdirectories = false, regExp = /^.//);

 index.routes.js \\首页模块路由
 login.routes.js \\ 登录模块路由
let routerList = []

function importAll(r) {
  r.keys().forEach(key => {
    routerList.push(r(key).default)
  });
}

importAll(require.context('./', false, /\.routes\.js/))

const routes = [
  ...routerList,
  {
    path: '/',
    name: 'home',
    component: Home
  }
]

 https://www.jianshu.com/p/c894ea00dfec

 
 



posted @ 2022-03-21 19:38  张小中  阅读(119)  评论(0编辑  收藏  举报