- function getComponent() {
+ async function getComponent() {
- return import(/* webpackChunkName: "lodash" */ 'lodash').then({ default: _ } => {
- const element = document.createElement('div');
-
- element.innerHTML = _.join(['Hello', 'webpack'], ' ');
-
- return element;
-
- }).catch(error => 'An error occurred while loading the component');
+ const element = document.createElement('div');
+ const { default: _ } = await import(/* webpackChunkName: "lodash" */ 'lodash');
+
+ element.innerHTML = _.join(['Hello', 'webpack'], ' ');
+
+ return element;
}
getComponent().then(component => {
document.body.appendChild(component);
});
---------------------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());
-------------------- 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"!'); };