• webpack 中 require.context() 的用法


    一、什么是 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 官方说明

    • 一个 webpack 的 api ,通过该函数可以获取一个上下文,从而实现工程自动化(遍历文件夹的文件,从中获取指定文件,自动导入模块)。
    • 在前端工程中,如果一个文件夹中的模块需要频繁引用时可以使用该中方式一次性引入

    二、如何使用

    • 语法
    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`.
    
    • 参数说明
    参数类型说明
    dirnameString需要读取模块的文件的所在目录
    useSubdirectoriesBoolean是否遍历子目录
    RegExpRegExp匹配的规则(正则表达式)
    • 返回值

    导出的函数有 3 个属性: resolve, keys, id.如下表所示

    属性类型说明
    resolveFunction接受一个参数request,request为文件夹下面匹配文件的相对路径,返回这个匹配文件相对于整个工程的相对路径
    keysFunction返回一个数组,由匹配成功的文件所组成的数组
    idString执行环境的 id
    • 用法示例
    function importAll(r) {
      r.keys().forEach(r);
    }
    
    importAll(require.context('../components/', true, /\.js$/));
    
  • 相关阅读:
    Intel关NUMA的内存编址
    16.成员内部类【20220624】
    51单片机学习:ADC模数转换实验--热敏电阻AD采集
    别再乱写git commit了
    75.颜色分类
    2022过半,Node你会用了吗
    React - 高级用法
    supervisor--go版安装
    【数据结构】结构体与链表
    单链表反转-算法题0001
  • 原文地址:https://blog.csdn.net/DarinZanya/article/details/139794424