Introduction to the usage of require.context (with examples)
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`)); }
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; }, {});
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")) })
What is the y method? Follow the clues and continue to look at the packaged code.
y = a("ae36");
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" },
"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" },
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
