7

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;
user10265865
  • 159
  • 2
  • 4
  • 11
  • What type of server are you using? Can your server generate the top of the page with all of the imports? How do you know what to call each variable and how to correlate it to the file you are importing? – Intervalia Nov 05 '18 at 20:19
  • No, ES6 doesn't have any FileSystem knowledge. But if you find yourself importing the same files again & again,. you could just create another one with them exported into an object literal. eg.. `import pages from '../pages'; const Contents = [one, two, three,...] = pages;` – Keith Nov 05 '18 at 20:23
  • could be a duplicate of this Q here https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack – Jaya Nov 05 '18 at 20:37
  • *"due to React being a non-server side language"* React is neither a language nor is involved in loading/processing module dependencies. – Felix Kling Nov 05 '18 at 20:46
  • 2
    Basically a duplicate of https://stackoverflow.com/q/29722270/218196 . However, if you are using React, you are likely using a module bundler. The bundler might be able to import a whole directory. You should tell us which bundler you are using (webpack, rollup, browserify, etc) – Felix Kling Nov 05 '18 at 20:48

1 Answers1

1

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/

  • That is so weird for me that this works like this. But then how would be do this with server side code in Nextjs for example? – Daniel Guedes Aug 05 '22 at 18:10