How to dynamically load modules in Babel and Webpack?

I am trying to use the dynamic module load function in ES6 and it seems that it is not yet implemented. But there are such replacements as the ES6 Module Loader Polyfill , which supposedly had to do the trick.

So, I have an ES6 project passed to ES5 using Babel and Webpack, and it works just fine on its own. But all my code is combined into one bundle.js file, which I would like to split into modules. And when I tried the mentioned Polyfill, it throws some error from the inside and the project does not even start.

index.js:6 Uncaught TypeError: Cannot read property 'match' of undefined 

And line 6 reads:

 var filePrefix = 'file:' + (process.platform.match(/^win/) ? '/' : '') + '//'; 

Here is my package.js file:

 { "dependencies": { "es6-module-loader": "^0.17.11", "events": "^1.1.0", "flux": "^2.1.1", "fs": "0.0.2", "react": "^15.0.2", "react-addons-css-transition-group": "^15.0.2", "react-dom": "^15.0.2", "react-router": "^2.4.0", "react-tap-event-plugin": "^1.0.0", }, "devDependencies": { "babel-core": "^6.8.0", "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.6.0", "babel-preset-react": "^6.5.0", "html-webpack-plugin": "^2.16.1", "react-hot-loader": "^1.3.0", "transfer-webpack-plugin": "^0.1.4", "webpack": "^1.13.0", } } 

Can someone tell me a working example of loading a dynamic module using Webpack and Babel?

+7
ecmascript-6 webpack babeljs es6-module-loader
source share
2 answers

There are really three things here ... dynamic import , lazy loading and code splitting / grouping. The System.import method populated with the ES6 module loader will allow dynamic import, but not dynamic code splitting :

However, most transpilers do not support the conversion of System.load calls to require.ensure , so you need to do this directly if you want to use dynamic code splitting.

Dynamic code separation is when you create child nodes at the entry point, which can then be dynamically lazy. For this, I would recommend using promise-loader , which is a little friendlier than require.ensure :

 import LoadEditor from 'promise?global,[name]!./editor.js'; ... if (page === 'editor') { LoadEditor().then(Editor => { // Use the Editor bundle... }) } 

Webpack now breaks the editor.js module and all its dependencies into a separate package that can be loaded immediately or dynamically (as shown above). Finally, depending on the size of the application, I think you should also consider vendor code splitting .

UPDATE

System.import been removed from the specification and replaced simply by import() . New webpack documents have a page that discusses dynamic imports in webpack and their limitations.

+5
source share

Example for lazy loading jQuery in ES6:

 import('jquery').then((jquery) => { window.$ = jquery.default; // Because jquery is the module, here is the new syntax for using this window.$('#id'); }); 
0
source share

All Articles