In the Vue project, webpack's require.context is used to implement batch introduction/import of images.

1. Background

In front-end projects, it is inevitable that dozens of icon or png types of images are needed. It would be too cumbersome to import them one by one. And webpackcan require.contextsolve this problem.

2. Structure

Static resource location and structure:
Insert image description here
Insert image description here
As shown in the figure, my goal is to import more than a dozen png images in mapDot in batches and obtain them accurately and quickly.

3. index.js implementation

const req = require.context('./mapDot', true, /\.png$/);
const pngHashMap = new Map();
req.keys().forEach((eachPng) => {
    
    
  const imgConfig = req(eachPng);
  const imgName = eachPng.replace(/^\.\/(.*)\.\w+$/, '$1');
  pngHashMap.set(imgName, {
    
     imgName, icon: req(eachPng).default || imgConfig });
});
export default pngHashMap;

Here we use the Map structure to access it, which is convenient for use after importing.

4. Import and use

import pngHashMap from '../../assets/images';
console.log(pngHashMap)

Insert image description here
As shown in the figure, the image in base64 format was finally obtained.

Guess you like

Origin blog.csdn.net/s18438610353/article/details/128459362