使用require.context()函数实现自动化导入

辰漪
2021-12-23 / 2 评论 / 279 阅读 / 正在检测是否收录...

require.context()

该函数接收三个参数

  1. directory {String} -读取文件的路径
  2. useSubdirectories {Boolean} -是否遍历文件的子目录
  3. regExp {RegExp} -匹配文件的正则

该函数执行后会返回一个函数,包含三个属性

  • resolve {Function} -接受一个参数request,request为test文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径
  • keys {Function} -返回匹配成功模块的名字组成的数组
  • id {String} -执行环境的id,返回的是一个字符串,主要用在module.hot.accept,应该是热加载

实际应用场景

vuex的module模块批量自动化导入

const files = require.context('./modules', false, /\.js$/) // 导入modules目录下所有的js文件
const modules = {} // 所有的store模块
// files.keys() 拿到 ['./account.js', './log.js']组成的数组
// 使用replace将./和.js替换为空,当做键名 files(key).default当做键值
files.keys().forEach(key => {
    //files(key).default 可以拿到每一个模块
  modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default
})
export default {
  namespaced: true,
  modules
}
1
选择打赏方式:
微信

评论 (2)

取消
  1. 头像
    辰漪 作者
    Windows 10 · Google Chrome

    1

    回复
    1. 头像
      纸鸢
      Windows 10 · Google Chrome
      @ 辰漪

      表情

      回复