首页 > 解决方案 > 是否可以在 React Typescript 中导入通配符路径?

问题描述

我想从通配符路径动态导入 React Typescript 组件,如下所示:-

const Component = loadable(
  () => import(`../../../src/**/*/${component_name}`),
);

是否可以使用通配符像上面一样导入?

在 Stackoverflow 中找到了很多解决方案,但没有一个符合要求。

任何帮助将不胜感激。

标签: javascriptreactjstypescriptimportreact-typescript

解决方案


你应该使用 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 需要默认导出

解决方案基于:

  1. https://reactjs.org/docs/code-splitting.html
  2. https://vuejs.org/v2/guide/components-registration.html

推荐阅读