簡體   English   中英

未捕獲的錯誤:使用JavaScript的動態導入時無法找到模塊

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

我正在使用Create-React-App,我希望使用webpack 2.0支持的動態import()來導入基於變量字符串的模塊。

我查看了官方提案( https://github.com/tc39/proposal-dynamic-import ),似乎可以這樣做:

import(`./language-packs/${navigator.language}.js`)

但是當我嘗試類似的東西時,它會破裂。

AppRoutes.js

import LazyLoad from 'services/LazyLoad';

export class AppRoutes extends React.Component {
  render() {
    return (
      <Switch>
        <Route
          exact path="/"
          render={(matchProps) => (
            <LazyLoad
              absoluteModulePath='pages/default/HomePage'
              getComponent={() => import('pages/default/HomePage')}
              {...matchProps}
            />
          )}
        />
      </Switch>
    );
  }
}

export default AppRoutes;

頁/默認/首頁/ index.js

import React from 'react';

export const HomePage = () => {
  return (
    <div>
      I'm the default HomePage
    </div>
  );
}

export default HomePage;

BROKEN 服務/ LazyLoad / index.js

import React from 'react';

export class LazyLoad extends React.Component {
  ...

  componentDidMount() {
    import(this.props.absoluteModulePath)  // Critical dependency: the request of a dependency is an expression
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  ...
}

export default LazyLoad;

錯誤:

在此輸入圖像描述

但是當我將LazyLoader更改為

工作 服務/ LazyLoad / index.js

import React from 'react';

export class LazyLoad extends React.Component {
  ...

  componentDidMount() {
    this.props.getComponent()
      .then(module => module.default)
      .then(AsyncModule => this.setState({AsyncModule}))
  }

  ...
}

export default LazyLoad;

有用。

在此輸入圖像描述

絕對路徑是在環境變量的幫助下內置到create-react-app中的東西。

.ENV

NODE_PATH=src/

我需要以這種方式動態加載模塊,以構建多租戶的概念證明。 如何修復損壞的LazyLoad,以便我可以將字符串作為prop傳遞並讓LazyLoad組件從該字符串prop中動態加載組件?

import()只允許部分動態語句。

在你的AppRoutes.js中你可以這樣做:

...
<LazyLoad
    modulePath='HomePage'
    getComponent={() => import('pages/default/HomePage')}
    {...matchProps}
/>

然后在你的LazyLoad組件中你做:

componentDidMount() {
  import(`pages/default/${this.props.modulePath}/index.js`)
    .then(module => module.default)
    .then(AsyncModule => this.setState({AsyncModule}))
}

完全動態的語句(例如import(foo))將失敗,因為webpack至少需要一些文件位置信息.import()必須至少包含有關模塊所在位置的一些信息,因此捆綁可以限制在特定目錄或一組文件。

https://webpack.js.org/api/module-methods/#import-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM