简体   繁体   English

动态导入组件错误-未捕获(承诺)错误:找不到模块

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

I made a react library converting menu data returned by microservice to dynamic route. 我做了一个反应库,将微服务返回的菜单数据转换为动态路由。

project structure image is below: 项目结构图如下:
--react-app --react-app
----node_modules ---- node_modules
------ ... ------ ...
------ rb-react ---> my react library ------ rb-react --->我的反应库
------ ... ------ ...
----src ---- src
------pages ------页
--------Dashboard.js -------- Dashboard.js
--------Prod.js -------- Prod.js
--------User.js -------- User.js
-------- ... -------- ...

library rb-react can not import pages, ie Dashboard.js 库rb-react无法导入页面,即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 v12.6.0
npm --version npm --version
6.11.3 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 Chrome控制台上的异常消息

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

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. 只有这样,webpack才能为该文件创建一个单独的块。 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. 如果您需要将所有模块加载到目录中,可以请签出require.context。 https://webpack.js.org/guides/dependency-management/ https://webpack.js.org/guides/dependency-management/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的错误:使用JavaScript的动态导入时无法找到模块 - Uncaught Error: Cannot Find Module When Using Dynamic Import for JavaScript 未捕获的错误:找不到模块“./components/LoginPage” - Uncaught Error: Cannot find module “./components/LoginPage” 路由模块停止工作:未捕获(承诺):错误:找不到“ xxxModule” - Routing module stop working: Uncaught (in promise): Error: Cannot find 'xxxModule' jsPDF 问题:未捕获(承诺中)错误:无法加载 dompurify:错误:找不到模块“dompurify” - Issue with jsPDF: Uncaught (in Promise) Error: Could not load dompurify: Error: cannot find module 'dompurify' 未捕获的错误:找不到模块&#39;openpgp&#39; - Uncaught Error: Cannot find module 'openpgp' 电子:未捕获错误:找不到模块 - Electron: Uncaught Error: Cannot find module 未捕获的错误:找不到模块“jquery” - Uncaught Error: Cannot find module 'jquery' 流星-未捕获的错误:找不到模块&#39;mongodb&#39; - Meteor - Uncaught Error: Cannot find module 'mongodb' 模块导入错误 - 找不到模块 - Module Import error - cannot find module Wasm: Uncaught (in promise) TypeError: Import #0 module=&quot;env&quot; error: module is not an object or function Promise.then (async) (anonymous) @ (index):9 - Wasm: Uncaught (in promise) TypeError: Import #0 module="env" error: module is not an object or function Promise.then (async) (anonymous) @ (index):9
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM