I want to import all pictures from a folder to a component with dynamic import like this:
index.js
const testFolder = './2020/';
const fs = require('fs');
const path = require('path');
const files = fs.readdirSync(testFolder);
const allowedExts = ['.png', '.jpg', 'svg'] // add any extensions you need
const modules = {};
if (files.length) {
let filterThruFiles = files.filter(file => allowedExts.indexOf(path.extname(file)) > -1)
filterThruFiles.forEach(file => modules[file] = `./${file}`);
}
module.exports = modules;
let modulesStringify = JSON.stringify(modules);
fs.writeFileSync('pics-url-list.json', modulesStringify);
I get an object with the paths and write it to a file, which works fine:
//pics-url-list.json
{
"1-1.jpg":"./1-1.jpg",
"1-2.jpg":"./1-2.jpg",
"1-3.jpg":"./1-3.jpg"
//and so on
}
but when I run npm start, I get this error. The main question is how to access this .json file in an React component? Now no console.log works in the App.js, it only show this error about fs.readdirSync
//App.js component
import picList from '../images/pics-url-list.json';
console.log(picList);
It is not possible to use fs like modules for client-side app.
There is a way to dynamically import all images by using require.context
For example,
function importAll(r) {
return r.keys().map(r);
}
const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With