javascript - 是否可以在 React Typescript 中导入通配符路径?
问题描述
我想从通配符路径动态导入 React Typescript 组件,如下所示:-
const Component = loadable(
() => import(`../../../src/**/*/${component_name}`),
);
是否可以使用通配符像上面一样导入?
在 Stackoverflow 中找到了很多解决方案,但没有一个符合要求。
任何帮助将不胜感激。
解决方案
你应该使用 React.lazy 和 Webpack 要求
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// registry for components
const components = {}
// Create component
const makeComponent => (path) => React.lazy(() => import(`${path}`));
// Get paths (Webpack)
const requireComponent = require.context(
'../../../components', // components folder
true, // look subfolders
/\w+\.([jt]sx)$/ //regex for files
)
requireComponent.keys().forEach(filePath => {
// Get component config
const Component = requireComponent(filePath);
// Get PascalCase name of component
const componentName = upperFirst(
camelCase(
// Gets the file name regardless of folder depth
filePath
.split('/')
.pop()
.replace(/\.\w+$/, '')
);
components[componentName] = Component;
)
此解决方案可能需要在您添加到组件文件夹的每个新组件后重新启动 Webpack。组件名称(在我们的例子中也就是文件名)应该是 uniq。React.lazy 需要默认导出
解决方案基于:
推荐阅读
- java - 每行从+7开始打印星形图案
- python - 在 Python 中实现井字游戏的 Minimax 算法
- r - rmarkdown 中的自定义突出显示样式
- python - 将变量分配给值的一部分
- html - 在 Angular 中,如何获取具有可扩展内容的 Mat-Table 上的行索引?
- python-3.x - 获取 urllib HTTP 错误 401 未经授权
- javascript - Google 表格:执行自定义功能时出现内部错误
- process - 绘制到 HelixViewPort3D 时出现 System.InvalidOperationException
- mp4 - 格式化 AVC/H.264 mdat
- time-complexity - 在没有指数膨胀的情况下将类型和值缩小在一起