0

I'm writing a React app using create-react-app.

Since I can do:

import LocalClass from "./localfolder/LocalClass.js"

and even (using dynamic import):

import('./localfolder/LocalClass.js').then((module) => { /* ... */ })

is there a way to list localfolder contents, so I can dynamically import the contained files?

The listing should happen at compile or bundling time, not at runtime (I'm thinking about an automatic menu creation feature).

The folder may contain plain classes too (i.e. not React components); I guess this is a matter of the bundler, but I'm not sure.

watery
  • 5,026
  • 9
  • 52
  • 92

2 Answers2

2

Since CRA uses Webpack under the hood, you could use require.context() to enumerate all loadable modules in a given path.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Interesting. I put together some [experimental code](https://stackoverflow.com/q/60710524/3127111), though I hit a roadblock on `dynamic imports`. – watery Mar 16 '20 at 17:29
0

Although it's kind of open-based, after some investigation

I found a lib: react-dynamic-import

Usage:

const loader = f => import(`./dynamic/${f}.js`);
|_ dynamic
|  |_ realComponent-en.js
|  |_ realComponent-eu.js
|  |_ realComponent-kn.js
|_ container.js <-- working file

Refer:

keikai
  • 14,085
  • 9
  • 49
  • 68
  • 1
    Thanks, I'm giving it a look. I may have non-React classes though - I'll edit the question. – watery Mar 15 '20 at 12:07
  • @watery you can use `regex` for the `filename` based filter for the `bundler`. And feel free to leave your feedback if you have further problems using the method mentioned above. – keikai Mar 15 '20 at 12:54
  • Did that post solved your problem? Kindly inform me if you have further questions about it. – keikai Mar 21 '20 at 04:12
  • Actually, I'm experimenting with [AXK's answer](https://stackoverflow.com/a/60692680/3127111). – watery Mar 21 '20 at 11:57
  • @watery Is this post still helpful for you? I'm cleaning my zero posts, trying to find out whether to remove this one or not – keikai Mar 21 '20 at 12:00
  • Well, I think it's too early to tell, but maybe this could anyway be useful to others. – watery Mar 21 '20 at 12:05