I want to import all pictures from a folder to a ponent 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 ponent? Now no console.log works in the App.js, it only show this error about fs.readdirSync
//App.js ponent
import picList from '../images/pics-url-list.json';
console.log(picList);
I want to import all pictures from a folder to a ponent 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 ponent? Now no console.log works in the App.js, it only show this error about fs.readdirSync
//App.js ponent
import picList from '../images/pics-url-list.json';
console.log(picList);
Share
Improve this question
asked Sep 4, 2020 at 13:28
GustėGustė
1373 silver badges13 bronze badges
2
-
fs
etc are node.js things and can only be done server-side. You can't work with the user's filesystem (through the browser) using those methods. – Joe Commented Sep 4, 2020 at 13:31 - @Joe so there's no way to do this? This is basically making a json file and accessing it in the ponent, there should be some other way maybe? – Gustė Commented Sep 4, 2020 at 13:43
1 Answer
Reset to default 6It 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)$/));