How are modules required in a React application using webpack asynchronously?

In a React application, I would like to import a library called flowtime.js only for a specific route / path, and then execute another code. This library has a dependency called Brav1toolbox. Also not available on npm.

My strategy is to use webpacks requirein a method componentDidMount. 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 leads to the following error.

Unprepared (in promise) ReferenceError: Brav1Toolbox not defined

So, Flowtime loads, but cannot find Brav1Toolbox.

I do not test with either reagent or web package, so maybe I have a wrong idea. I am trying to use webpack only to download these libraries if my users visit the path where these libraries are needed. This is the webpack guide I used as a reference.

Thanks for the help.

+4
source share
1 answer

It depends on your version of the web package, but you are on the right track with code / routing separation.

For webpack v2, I would recommend checking out the Webpack documentation .

webpack 2 /, , . , agent- , . "/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");
}} />
+1

Source: https://habr.com/ru/post/1652930/


All Articles