Lazy loading is very important for page optimization, when some resources that are not needed at first should not be downloaded together in the main file, but wait to be downloaded when they are used. Lazy loading can reduce the size of the main file, speed up the first screen display, relieve the pressure on the server and other advantages. Lazy loading of Webpack is achieved through dynamic imports. Print.js: print.js

console.log( 'The print.js module has loaded! See the network tab in dev tools... '); export default () => { console.log('Button Clicked: Here\'s "some text"! '); };Copy the code

index.js:

import _ from 'lodash'; function component() { const element = document.createElement('div'); const button = document.createElement('button'); const br = document.createElement('br'); button.innerHTML = 'Click me and look at the console! '; element.innerHTML = _.join(['Hello', 'webpack'], ' '); element.appendChild(br); element.appendChild(button); // Note that because a network request is involved, some indication // of loading would need to be shown in a production-level site/app. button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => { const print = module.default; print(); }); return element; } document.body.appendChild(component());Copy the code

Run WebPack, then click the on-screen button to open the Network panel and see all the resources that were originally loaded:

Then click the button on the screen, and then look at the loaded resource, find an extra file, this is the dynamic import module will be lazy load: