简体   繁体   English

如何在 React 或 create-react-app 中列出源文件夹内容?

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

I'm writing a React app using create-react-app .我正在使用create-react-app编写一个 React 应用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?有没有办法列出localfolder文件localfolder内容,以便我可以动态导入包含的文件?

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 (ie not React components);该文件夹也可能包含普通类(即不是 React 组件); I guess this is a matter of the bundler, but I'm not sure.我想这是打包程序的问题,但我不确定。

由于 CRA 在幕后使用 Webpack,您可以使用require.context()枚举给定路径中的所有可加载模块。

Although it's kind of open-based, after some investigation虽然它是基于开放的,但经过一些调查

I found a lib: react-dynamic-import我找到了一个库: 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:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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