问题
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.
回答1:
Since CRA uses Webpack under the hood, you could use require.context() to enumerate all loadable modules in a given path.
回答2:
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:
react document code-splitting
related QA
来源:https://stackoverflow.com/questions/60692552/how-can-i-list-source-folder-contents-in-react-or-create-react-app