Home > Web Front-end > JS Tutorial > Introduction to the usage of require.context (with examples)

Introduction to the usage of require.context (with examples)

不言
Release: 2019-03-26 09:46:54
forward
5163 people have browsed it

This article brings you an introduction to the usage of require.context (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Cause: Why is the management feature of webpack suddenly used?

A certain page of the project needs to introduce N demo pictures. That is, batch import of resources: If you want to import more than 10 image resources, you need to write 10 import codes as follows: import XXX from 'relative/path/assets/imgs/xxx';, then if there are more static resources Need to introduce it? This is where require.context comes in handy.

Documentation

The introduction of the official document is here first, but you can take a look at it to understand the usage posture.

Let’s take a look at Chestnut

Without further ado, let’s look at the code for the above scenario.

The scenario requires us to import all webp format pictures under a specified folder, display x case pictures under demo1 when clicking demo1, and display x pictures under demoX when clicking demoX Case diagram.

    // 通过require.context的方式引入指定的路径下匹配到的模块引用
    const demoImgsContext = require.context('@src/assets/imgs/demo', false, /\.webp$/);
    ...
    // 使用姿势
    trigger(type) {
        this.demoImgs = Arry.from({length: config.type}, (key, value) => value + 1)
            .map(index => demoImgsContext(`./${type}_demo${index}.webp`));
    }
Copy after login

Is there still a need for scenes that draw inferences from one example?
For example, vuex introduces multiple module stores. This method can also be used.

    // 添加module文件是,文件命请按照module_XXX的方式命名
    // 自动引入module文件夹下的js文件
    const mutationContext = require.context('./module', false, /.*\.js/);
    const modules = mutationContext.keys().reduce((prev, cur) => {
        // 排除module_root文件
        const matches = cur.match(/module_(?!.*root)(\w+)\.js/);
        const key = matches && matches[1];
        key && (prev[key] = mutationContext(cur).default);
        return prev;
    }, {});
Copy after login

Next, let’s take a look at how require.context dynamically introduces resources?

Look at the packaged dist directory to see what the code for the chunk part of our static image case looks like.

The code that references module resources in the trigger method is as follows. The y method is called and the path of a resource is passed in.

    map(function (e) {
        return y("./".concat(t, "_demo").concat(e, ".webp"))
    })
Copy after login

What is the y method? Follow the clues and continue to look at the packaged code.

   y = a("ae36");
Copy after login

y method is the export of a certain module, continue to view the module code under this ID:

ae36: function (t, e, a) {
      // 此处是一个map映射,key值和真正的资源id的映射
      var i = {
        "./a_module_demo1.webp": "6085",
        "./a_module_demo2.webp": "fd3b",
        "./b_module_demo1.webp": "cbf6",
        "./b_module_demo2.webp": "220e",
        "./c_module_demo1.webp": "273e",
        "./c_module_demo2.webp": "5a5e",
        "./d_module_demo1.webp": "75b0",
        "./d_module_demo2.webp": "2d3e"
      };
      // 此处根据module的id值,真正require一个资源
      function r(t) {
        var e = o(t);
        return a(e)
      }
      
      function o(t) {
        var e = i[t];
        if (!(e + 1)) {
          var a = new Error("Cannot find module '" + t + "'");
          throw a.code = "MODULE_NOT_FOUND", a
        }
        return e
      }
      r.keys = function () {
        return Object.keys(i)
      }, r.resolve = o, t.exports = r, r.id = "ae36"
    },
Copy after login

"6085", "fd3b" and other map mapped value values ​​can be imagined, is the real resource id value, and its corresponding module mapping is as follows:

6085: function (t, e) {
      t.exports =
        "//${你配置的项目publicPath}/img/1_module_demo1.ed6db768.webp"
    },
Copy after login

When the user triggers the trigger method, based on the values ​​specified by type and index, the module resource reference stored in require.context will find the real resource reference based on the key value. Resource module, require, the browser will help us download the corresponding resources, achieving the idea of ​​loading on demand after being introduced in batches.

This article has ended here. For more other exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!

The above is the detailed content of Introduction to the usage of require.context (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template