Dynamic imports

Dynamic imports are, essentially, on-demand imports on Webpack. If you have already bundled a lot of code but need to patch more to it, the dynamic import method will come to the rescue. This also includes dynamic code splitting, which, as it sounds, means splitting code and optimizing it after a bundle has been built.

Webpack 5 supports two methods of doing this:

  • The first method uses the import() syntax, which conforms to the dynamic import proposal for ECMAScript.
  • The second is the webpack-specific approach, which uses the require.ensure method (this is a legacy method).

The following is an example of the first approach; the goal is to demonstrate a modern method of using dynamic imports, which will be more common on recent projects.

The import() call is an internal call to promises. A promise refers to the information returned from a loader. 

When using import() with older browsers, use a polyfill function—such as es6-promise or promise-polyfill—to shim promiseshim-loader is a loader that transforms code so that it works in the Webpack 5 environment; this works similarly to doing this manually with imports-loader and exports-loader.

The next step is to remove any surplus entries in the configuration file, which includes the optmization.splitChunks reference, as it will not be needed in the following demonstration:

  1. Now, open the webpack.config.js file and make the following entries:
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js'
index: './src/index.js',
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
};

Note the use of chunkFilename, which determines the name of non-entry chunk files.

The preceding configuration was needed to prepare your project to use dynamic imports. Be sure to remove the text in bold as you may see this when working with the same code, as before.

Jumping back into the project, we need to update it with instructions to remove unused files. 

You may have already set up your practice directory; however, it is recommended that you start with a fresh set of directories that doesn't contain any experimental code.

The following demonstration will use dynamic importing to separate a chunk, instead of the static importing of lodash.

  1. Open the index.js file and ensure the following entries are made:
function getComponent() {
return import(/* webpackChunkName: "lodash" */ 'lodash').then((
{ default: _ }) => {

var element = document.createElement('div');

element.innerHTML = _.join(['Hello', 'Webpack'], ' ');

return element;

}).catch(error => 'An error occurred while loading
the component');

}

getComponent().then(component => {
document.body.appendChild(component);
})

When importing a CommonJS module, this import will not resolve the value of module.exports; instead, an artificial namespace object will be created. Therefore, we need a default when importing.

The use of webpackChunkName in the comment will cause our separate bundle to be named lodash.bundle.jsinstead of just [your id here].bundle.js. For more information on webpackChunkName and the other available options, see the import() documentation.

If Webpack is now run, lodash will separate into a new bundle.

  1. npm run build can be run using your command-line interface (CLI). In your CLI utility, type the following:
npm run build

When a build is run, you should see the following message:

...
Asset Size Chunks Chunk Names
index.bundle.js 7.88 KiB index [emitted] index
vendors~lodash.bundle.js 547 KiB vendors~lodash [emitted] vendors~lodash
Entrypoint index = index.bundle.js
...

import() can be used with asynchronous functions as it returns a promise. This requires the use of a preprocessor, such as the syntax-dynamic-import Babel plugin. 

  1. Using src/index.js, make the following amendments to show how the code can be simplified:
async function getComponent() {
'lodash').then(({ default: _ }) => {
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);
});

The preceding example uses the same file that we used in the Dynamic imports section. We have turned multi-line code into single lines, replaced a returning function with asynchronous code, expediting our coding practice. You will see that it is now much simpler than the earlier code—it uses the same file, src/index.js, and achieves the same thing.

We often simplify code to help with loading times. Another key way of improving browsing speed is caching.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.250