如何在React或create-react-app中列出源文件夹的内容? [英] How can I list source folder contents in React or create-react-app?

查看:120
本文介绍了如何在React或create-react-app中列出源文件夹的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 create-react-app 编写React应用。

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

因为我可以这样做:

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

甚至(使用动态导入):

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

有没有办法列出 localfolder 的内容,这样我就可以动态导入包含的文件了吗?

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).

该文件夹也可能包含普通类(即,不是React组件);或者在运行时(我正在考虑一种自动菜单创建功能)。我想这是捆绑器的问题,但我不确定。

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.

推荐答案

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

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

这篇关于如何在React或create-react-app中列出源文件夹的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆