Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import all files from a directory in ES6?

Without getting into the code, I have a weird circumstance where a Framework using ReactJS will be importing a unknown number of files based on its use case. Some times a developer may have 5 file they want to import, some times its 2....

Due to this, one Component is essentially importing the files in a bunch like below. Is there a way to write code that says "import all files from the pages directory" by iterating through them all? I understand this is likely impossible due to React being a non-server side language, but there has to be at least a better way to import them...

side note, the names do not matter on the imports as seen

import one from '../pages/1_1';
import two from '../pages/2_1';
import three from '../pages/3_1';
import four from '../pages/4_1';
import five from '../pages/5_1';
import six from '../pages/6_1';
import seven from '../pages/7_1';
import eight from '../pages/8_1';

const Contents = [one,two,three,four,five,six,seven,eight];

export default Contents;
like image 705
user10265865 Avatar asked Nov 08 '22 00:11

user10265865


1 Answers

There is no way (without server-side code) that the JS running in your browser could know the folder structure of a filesystem. Thus "import all file from folder" is not possible. What you can do is to import (manually) all file in a module and manage the module itself.

Ref: https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/

like image 168
Antonio Buelli Avatar answered Nov 14 '22 11:11

Antonio Buelli