簡體   English   中英

是否可以在 React Typescript 中導入通配符路徑?

[英]Is it possible to import wildcard path in 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 需要默認導出

解決方案基於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM