【问题标题】:Is it possible to import wildcard path in React Typescript?是否可以在 React Typescript 中导入通配符路径?
【发布时间】:2020-10-12 05:14:02
【问题描述】:
我想从 通配符路径 动态导入 React Typescript 组件,如下所示:-
const Component = loadable(
() => import(`../../../src/**/*/${component_name}`),
);
是否可以像上面那样使用通配符导入?
在 Stackoverflow 中找到了很多解决方案,但没有一个符合要求。
任何帮助将不胜感激。
【问题讨论】:
标签:
javascript
reactjs
typescript
import
react-typescript
【解决方案1】:
你应该使用 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 需要默认导出
解决方案基于:
- https://reactjs.org/docs/code-splitting.html
- https://vuejs.org/v2/guide/components-registration.html