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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I put together some experimental code, though I hit a roadblock on dynamic imports.
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:

6 Comments

Thanks, I'm giving it a look. I may have non-React classes though - I'll edit the question.
@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.
Did that post solved your problem? Kindly inform me if you have further questions about it.
Actually, I'm experimenting with AXK's answer.
@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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.