Dynamic import in react not working when trying to import a component in another directory

There’s limitation when using dynamic imports with variable parts.

Webpack Docs

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located. Bundling can be limited to a specific directory or set of files so that when you are using a dynamic expression - every module that could potentially be requested on an import() call is included.For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

In your case, during build time for dynamic import in FirstComponent component, bundling was limited to directory where the FirstComponent component was i.e. Components directory.

What it means is that, webpack will find all the files that are in the Components directory and then create chunks for them. Then at runtime when dynamic import is called, webpack will serve the chunk that corresponds to the value passed in.

Since you passed path= '../FooterComp/Footer' has no corresponding chunk so webpack will throw the error.

This is also same for Dynamic component. If you try to dynamically import with variable parts for the files that are outside src folder, you will get same error.

So to solve this you have couple of options

  1. place both files in same folder

i.e

'src/Components/FirstComponent.js'

'src/Components/Footer.js'

And use

// In FirstComponent.js
   componentDidMount() {
      const { path } = this.props;
      import(`${path}`)
      .then(module => this.setState({ module: module.default }))   
   }


{Component && <Component path='./Footer' />} // Index.js
  1. be more specific as possible

i.e

// In FirstComponent.js
 componentDidMount() {
      const { path } = this.props;
      import(`../FooterComp/${path}`)
      .then(module => this.setState({ module: module.default }))   
 }

And use

{Component && <Component path='Footer' />} //  In index.js