How can I list source folder contents in React or create-react-app?

╄→гoц情女王★ 提交于 2020-05-14 09:08:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!