Dynamic import components error - Uncaught (in promise) Error: Cannot find module

yakebao

I made a react library converting menu data returned by microservice to dynamic route.

project structure image is below:
--react-app
----node_modules
------ ...
------ rb-react ---> my react library
------ ...
----src
------pages
--------Dashboard.js
--------Prod.js
--------User.js
-------- ...

library rb-react can not import pages, ie Dashboard.js

        let rootPath = path.resolve(__dirname, '../src/pages');

        let menuPath = menuCommand.replace('#', '');
        let importObject = asyncComponent(() =>
          import(rootPath + '/' + menuCommand.split('/')[1])
        );
        if (isEmpty(routeResultArray)) {

          routeResultArray.push(
            <Route key={menuKey} exact path='/' component={importObject} />
          );
        }

node --version
v12.6.0
npm --version
6.11.3

Here is some code of my project

dynamic import class

export default function asyncComponent(importComponent) {

  class RbImport extends Component {

    constructor(props) {

      super(props);

      this.state = {
        component: null
      };
    }

    async componentDidMount() {

      const { default: component } = await importComponent();

      this.setState({

        component: component
      });
    }

    render() {

      const C = this.state.component;

      return C ? <C {...this.props} /> : <></>;
    }
  }

  return RbImport;
}

dynamic route

import React from 'react';
import path from 'path';
import { HashRouter, Route, Switch } from 'react-router-dom';
import ScrollToTop from './ScrollToTop';
import App from '../../App';
import { RbLibraryComponent } from './RbLibraryComponent';
import { RbLocalStorage } from '../util/RbLocalStorage';
import { NotFound } from '../notfound/NotFound';
import { isEmpty } from '../util/RbUtil';
import asyncComponent from '../util/RbImport';

export class RbRoute extends RbLibraryComponent {

  constructor() {
    super();
    this.state = {};

    this.RbLocalStorage = new RbLocalStorage();
    this.composeRoute = this.composeRoute.bind(this);
    this.recursiveComposeRoute = this.recursiveComposeRoute.bind(this);
  }

  composeRoute() {

    let routeResultArray = [];
    let userMenus = this.RbLocalStorage.loadUserMenu();

    this.recursiveComposeRoute(routeResultArray, userMenus, null);
    return routeResultArray;
  }

  recursiveComposeRoute(routeResultArray, menuDataList, prefixKey) {

    if (isEmpty(menuDataList)) {

      return;
    }

    prefixKey = isEmpty(prefixKey) ? '' : prefixKey;

    let userMenuCount = menuDataList.items.length;
    for (let idx = 0; idx < userMenuCount; idx++) {

      let userMenu = menuDataList.items[idx];

      if (isEmpty(userMenu)) {

        continue;
      }

      let menuKey = isEmpty(prefixKey) ? idx : prefixKey + '-' + idx;

      let menuCommand = userMenu.command;
      if (isEmpty(menuCommand)) {
        //nothing
      } else {

        let rootPath = path.resolve(__dirname, '../src/pages');

        let menuPath = menuCommand.replace('#', '');
        let importObject = asyncComponent(() =>
          import(rootPath + '/' + menuCommand.split('/')[1])
        );
        if (isEmpty(routeResultArray)) {

          routeResultArray.push(
            <Route key={menuKey} exact path='/' component={importObject} />
          );
        }

        routeResultArray.push(
          <Route key={menuKey} path={menuPath} component={importObject} />
        );
      }

      if (isEmpty(userMenu.items)) {
        //nothing
      } else {

        this.recursiveComposeRoute(routeResultArray, userMenu, menuKey);
      }
    }
  }

  render() {

    let { menu, productionName, userName } = this.props;

    if (menu === null || menu === undefined) {
      return <></>;
    }

    return (
      <HashRouter>
        <ScrollToTop>
          <App menu={menu} userName={userName}>
            <Switch>
              {this.composeRoute()}
              <Route component={NotFound} />
            </Switch>
          </App>
        </ScrollToTop>
      </HashRouter>
    );
  }
}

export default RbRoute;

Exception Message at Chrome Console

Uncaught (in promise) Error: Cannot find module '/src/pages/Dashboard'
    at webpackContextResolve (^.*$:29)
    at webpackContext (^.*$:24)
    at RbRoute.js:221 --> (Compiled Source) return _interopRequireWildcard(require("".concat(rootPath + '/' + menuCommand.split('/')[1])));

Avanish Pai

If you are trying to use async import, you would need to specify the path to the file that you are trying to import. Only then , webpack would be able to create a separate chunk for that file. Here, the way i understand, you are trying to make your import statements dynamic. That would not work. You would need to specify the full path of each of the async import that you make. (this path needs to be available at build time)

Could you please check out require.context if you need to load all modules in a directory. https://webpack.js.org/guides/dependency-management/

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Javascript

Uncaught (in promise): Error: Cannot read property of undefined

From Dev

Uncaught (in promise): Error: Cannot find primary outlet to load 'AchivementComponent'

From Dev

EXCEPTION: Uncaught (in promise): Error: Cannot find module 'app/home/home.module'

From Dev

Uncaught (in promise): Error: Cannot match any routes: ' '

From Dev

Uncaught Error: Cannot Find Module When Using Dynamic Import for JavaScript

From Dev

Uncaught Error: Cannot find module "fs" when using webpack

From Dev

Ionic Uncaught Error: Cannot find module "." when importing a service provider

From Dev

Uncaught Error: Cannot find module 'stream'

From Dev

Simple absolute import causing 'Cannot find module' error

From Dev

Ionic3 - Uncaught Error: Cannot find module '.'

From Dev

Ionic 4 / Angular Routing: ERROR Error: Uncaught (in promise): Error: Cannot find 'EventHomePageModule' in './home/home.module'

From Dev

React and Docker - Uncaught Error: Cannot find module 'react-player'

From Dev

Issue with jsPDF: Uncaught (in Promise) Error: Could not load dompurify: Error: cannot find module 'dompurify'

From Dev

webpacker Uncaught Error: Module build failed / Cannot find module 'babel-plugin-syntax-dynamic-import'

From Dev

Uncaught Error: Cannot find module 'redux'

From Dev

Uncaught Error: Cannot find module "./RandomWords"

From Dev

Error: Cannot find module './'

From Dev

Where is the error that is resulting in this Uncaught Error: Cannot find module "./users/UserSection.jsx" message?

From Dev

Meteor Error: Uncaught Error: Cannot find module 'component.jsx'

From Dev

Uncaught Error: Cannot find module 'openpgp'

From Dev

Routing module stop working: Uncaught (in promise): Error: Cannot find 'xxxModule'

From Dev

Console error "Uncaught Error: Cannot find module "/axios" at webpackMissingModule" with react

From Dev

ERROR Error: Uncaught (in promise): Error: Cannot find module './user/user.module'

From Dev

"Uncaught SyntaxError: Cannot use import statement outside a module" error in reactjs

From Dev

Uncaught Error: Cannot find module './imgShop/X React

From Dev

Uncaught Error: Cannot find module './recipes' in React Native

From Dev

Uncaught Error: Cannot find module 'firebase'

From Dev

Why do I get a "cannot find module" error when doing a dynamic import in TypeScript?

From Dev

Parcel 2 - Uncaught Error: Cannot find module 'axios'

Related Related

  1. 1

    Uncaught (in promise): Error: Cannot read property of undefined

  2. 2

    Uncaught (in promise): Error: Cannot find primary outlet to load 'AchivementComponent'

  3. 3

    EXCEPTION: Uncaught (in promise): Error: Cannot find module 'app/home/home.module'

  4. 4

    Uncaught (in promise): Error: Cannot match any routes: ' '

  5. 5

    Uncaught Error: Cannot Find Module When Using Dynamic Import for JavaScript

  6. 6

    Uncaught Error: Cannot find module "fs" when using webpack

  7. 7

    Ionic Uncaught Error: Cannot find module "." when importing a service provider

  8. 8

    Uncaught Error: Cannot find module 'stream'

  9. 9

    Simple absolute import causing 'Cannot find module' error

  10. 10

    Ionic3 - Uncaught Error: Cannot find module '.'

  11. 11

    Ionic 4 / Angular Routing: ERROR Error: Uncaught (in promise): Error: Cannot find 'EventHomePageModule' in './home/home.module'

  12. 12

    React and Docker - Uncaught Error: Cannot find module 'react-player'

  13. 13

    Issue with jsPDF: Uncaught (in Promise) Error: Could not load dompurify: Error: cannot find module 'dompurify'

  14. 14

    webpacker Uncaught Error: Module build failed / Cannot find module 'babel-plugin-syntax-dynamic-import'

  15. 15

    Uncaught Error: Cannot find module 'redux'

  16. 16

    Uncaught Error: Cannot find module "./RandomWords"

  17. 17

    Error: Cannot find module './'

  18. 18

    Where is the error that is resulting in this Uncaught Error: Cannot find module "./users/UserSection.jsx" message?

  19. 19

    Meteor Error: Uncaught Error: Cannot find module 'component.jsx'

  20. 20

    Uncaught Error: Cannot find module 'openpgp'

  21. 21

    Routing module stop working: Uncaught (in promise): Error: Cannot find 'xxxModule'

  22. 22

    Console error "Uncaught Error: Cannot find module "/axios" at webpackMissingModule" with react

  23. 23

    ERROR Error: Uncaught (in promise): Error: Cannot find module './user/user.module'

  24. 24

    "Uncaught SyntaxError: Cannot use import statement outside a module" error in reactjs

  25. 25

    Uncaught Error: Cannot find module './imgShop/X React

  26. 26

    Uncaught Error: Cannot find module './recipes' in React Native

  27. 27

    Uncaught Error: Cannot find module 'firebase'

  28. 28

    Why do I get a "cannot find module" error when doing a dynamic import in TypeScript?

  29. 29

    Parcel 2 - Uncaught Error: Cannot find module 'axios'

HotTag

Archive