Code separation with dynamic modules?

I am using the Webpack code splitting feature in React. I am creating an application in which the user selects an option and the corresponding React component displays. However, I find that using CommonJs require.ensure only works with hard-coded strings. When I use variables, it seems to work, the components turn off. But when I look at a tab on the network, I see that it does not break the code - it does not download new packages. Where, when I program hard, every time a call comes up for a new package.

Here is what works:

 executeDynamic(component){ var that = this; switch(component){ case 'SolidButton': require.ensure([], function(require){ DynamicModule = require(`./elements/SolidButton/index.js`); that.forceUpdate(); }); break; case 'ThreeDButton': require.ensure([], function(require){ DynamicModule = require(`./elements/ThreeDButton/index.js`); that.forceUpdate(); }); break; case 'NoPreview': require.ensure([], function(require){ DynamicModule = require(`./elements/NoPreview/index.js`); that.forceUpdate(); }); break; default: break; } } 

Here is what I want to work:

 executeDynamic(component){ var that = this; require.ensure([], function(require) { DynamicModule = require(`./elements/${component}/index.js`); that.forceUpdate(); }); } 
+8
reactjs webpack commonjs
source share
1 answer

I finally get it! I moved the dynamic request to my own file, so below is my call to this file from my responsive component, and then the contents of the file. For this you need the bundle-loader package.

So, this is where I make the call, passing this along with the name of the component I want to load.

 loadLiveCode(that, component) { req(component, function(result) { DynamicModule = result; that.forceUpdate(); }); } 

And the dynamicRequire.js file that contains our dynamic call uses the bundle-loader utility:

 module.exports = function loadAsync(expr, callback) { var bundledResult = require("bundle!./elements/" + expr + "/index.js"); bundledResult(function(result) { callback(result); }); }; 
+3
source share

All Articles