I've a reactjs project, this code: "const images = require.context('./imgs', false);…
- User
I've a reactjs project, this code: "const images = require.context('./imgs', false); const imageList = images.keys().map(image => images(image));" attaches an unnecessary hash after every image imported, I don't want that, how can i prevent this?
- Assistant
In React, importing images with
require.contextgenerates a unique hash for every imported image. This hash is added to the file name as a way to ensure that the imported images have a unique identifier.If you do not want this hash appended to your image URLs, you can modify your code to remove it by using a regular expression. Here's an example of how you can achieve that:
jsxconst images = require.context('./imgs', false); const imageList = images.keys().map(image => { const imagePath = images(image); const imageName = imagePath.slice(imagePath.lastIndexOf('/') + 1); // Get only the image file name const imageWithoutHash = imageName.replace(/(\.[a-z0-9]+)-\w{20}(\.[a-z]+)/, '$1$2'); // Remove the hash from the file name return images(`./${imageWithoutHash}`); // Import the image with the modified file name });