简体   繁体   中英

Is it possible to import wildcard path in React Typescript?

I want to import dynamically React Typescript Component from wildcard path like below:-

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

Is it possible to import like above using a wildcard?

Lots of solutions found in Stackoverflow but nothing match with the requirement.

Any help will highly appreciate.

You should use React.lazy and Webpack require

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

This solution may require restart Webpack after each new component that you add to components folder. Component names (aka fileNames in our case) should be uniq. React.lazy required default export

Solution based on:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM