Is it possible to import wildcard path in React Typescript?

1.7k views Asked by At

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.

1

There are 1 answers

2
Gleb Shaltaev On BEST ANSWER

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 = makeComponent(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