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 webpack
can require.context
solve this problem.
2. Structure
Static resource location and structure:
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)
As shown in the figure, the image in base64 format was finally obtained.