webpack 之 require.context 用法

    最近项目中用到了vue-element-admin当作框架,当中有一个很好的例子:封装了一个svg的组件,其中就是用到了require.context,然后就出查了相关的介绍,当时也是一头雾水,最后决定弄明白这个东西。

  | 看下webpack官方的介绍:

 

require.context 点击打开链接

You can create your own context with the require.context() function.

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 parses for require.context() in the code while building.

The syntax is as follows:

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

Examples:

require.context("./test", false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request endings with `.test.js`.
require.context("../", true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js

 

    啥意思呢,就是说啊,这玩意的目的啊就是为了省事,通常我们可能会在多个页面require 同一个组件,数量少还行,多了的话就很蛮烦,维护起来也费劲。这个时候require.context 就排上用场了,一次性引入。

 

   | 首先介绍下入参 :

        1. 你要引入文件的目录

        2.是否要查找该目录下的子级目录

        3.匹配要引入的文件

   | 返回值是一个function:

function webpackContext(req) {
	return __webpack_require__(webpackContextResolve(req));
}

    这个function有三个属性:resolve 、keys、id

        · resolve: 是一个函数,他返回的是被解析模块的id

        · keys: 也是一个函数,他返回的是一个数组,该数组是由所有可能被上下文模块解析的请求对象组成

        · id:上下文模块的id

     | 用法:

 

         拿该目录为例

         

           要引入svg下面所有的svg文件:

            在该文件(icons)目录下新建一个js文件index.js 写如下代码:

let requireAll = requireContext => requireContext.keys().map(requireContext)
let req = require.context('./svg', false, /\.svg$/)
requireAll(req)

我们只需要将改index.js 引入,就可以将svg目录下所有的svg文件都引入到项目中了。

 

 

 

 

 

 

 

 

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值