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);