简体   繁体   中英

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;

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM