简体   繁体   English

如何使用webpack在React应用程序中异步需要模块?

[英]How to asynchronously require modules in React application using webpack?

In a React application, I would like to import a library called flowtime.js only for a certain route/path and then execute some more code. 在React应用程序中,我想只为某个路径/路径导入一个名为flowtime.js的库,然后再执行一些代码。 This library has a dependency called Brav1toolbox . 该库有一个名为Brav1toolbox的依赖 Neither is available on npm. 在npm上都没有。

My strategy is to use webpack's require in the Component's componentDidMount method. 我的策略是在Component的componentDidMount方法中使用webpack的require Here is my attempt : 这是我的尝试:

componentDidMount() {
  require.ensure([ 'local/relative/path/to/lib/brav1toolbox.js'], function(require) {
    var f = require('local/relative/path/to/other/lib/Flowtime.js/js/flowtime.js');
  });
}

which results in the following error. 这会导致以下错误。

Uncaught (in promise) ReferenceError: Brav1Toolbox is not defined 未捕获(承诺)ReferenceError:未定义Brav1Toolbox

So Flowtime is being loaded but is not able to find Brav1Toolbox. 所以正在加载Flowtime但无法找到Brav1Toolbox。

I am not experienced with either React or webpack so perhaps I have a misconception. 我对React或webpack都没有经验,所以也许我有一个误解。 I am trying to use webpack to only load those libraries if my users visit a path where those libraries are needed. 我试图使用webpack只加载那些库,如果我的用户访问需要这些库的路径。 This is the webpack guide I used as reference. 这是我用作参考的webpack指南

Thank you for trying to help. 感谢您的帮助。

It depends on your version of webpack, but you are on the right track with code splitting / route chunking. 这取决于你的webpack版本,但你在正确的轨道上进行代码拆分/路由分块。

For webpack v2, I would recommend checking out the Webpack documentation . 对于webpack v2,我建议您查看Webpack文档

With webpack 2 you can require the libraries within the react containers / components where they are needed, and then dynamically load the code based on the path. 使用webpack 2,您可以在需要它们的反应容器/组件中需要库,然后根据路径动态加载代码。 An example of how you might be able to do this with react-router via two example routes, eg "/home" and "/about", is below: 有关如何使用react-router通过两个示例路由(例如“/ home”和“/ about”)执行此操作的示例如下:

<Route path="/home" getComponent={(nextState, callback) => {
    require.ensure([], require => {
        callback(null, require("./containers/home"));
    }, "Home");
}} />
<Route path="/about" getComponent={(nextState, callback) => {
    require.ensure([], require => {
        callback(null, require("./containers/about"));
    }, "About");
}} />

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM