Adding a utility

In this context, a utility means a file or module that is responsible for a related set of functions, designed to optimize, analyze, configure, or maintain. This is in contrast to an application, which tends to perform a task or set of tasks aimed directly at users. Therefore, you may think of a utility, in this context, as something that is part of the frontend but is hidden away in the background for background tasks.

To begin, add a utility file to the example project. Do this in src/math.js so that it exports two functions:

  1. The first step will be to organize the project directory:
webpack5-demo
|- package.json
|- webpack.config.js
|- /dist
  |- bundle.js
  |- index.html
|- /src
  |- index.js
  |- math.js
|- /node_modules

The project tree shows how your files and folder should look and you will note some new additions in there, such as math.js.

  1. Let's now take a closer look at how math.js is coded:
export function square(x) {
  return x * x;
}

export function cube(x) {
  return x * x * x;
}

You'll see that they are simple-to-export functions; they will come to the fore later.

  1. Also, make sure you set the Webpack mode to development in the configuration file, webpack.config.jswhich ensures the bundle is not minified:
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
  },
  mode: 'development',
  optimization: {
    usedExports: true
  }
};
  1. With this in place, we next update the entry script to utilize one of these new methods and remove lodash for simplicity. This is done using the src/index.js file:
  import _ from 'lodash';
  import { cube } from './math.js';

  function component() {
    const element = document.createElement('div');
    const element = document.createElement('pre');

    // Lodash, now imported by this script
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    element.innerHTML = [
      'Hello Webpack!',
      '5 cubed is equal to ' + cube(5)
    ].join('

');

    return element;
  }

  document.body.appendChild(component());

From the proceeding example, we can see that the square method was not imported from the src/math.js module. This function can be considered dead code—essentially, an unused export that can be dropped.

  1. Now, run an npm build again to inspect the results:
npm run build
  1. Once that is done, locate the dist/bundle.js file—it should be somewhere on lines 90–100. Search the file for code similar to the following example to follow this process:
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
  'use strict';
  /* unused harmony export square */
  /* harmony export (immutable) */ __webpack_exports__['a'] = cube;
  function square(x) {
    return x * x;
  }

  function cube(x) {
    return x * x * x;
  }
});

In this example, you will now see an unused harmony export square comment. Note that it is not being imported. It is, however, still included in the bundle for the time being. 

  1. ECMA scripting is not perfect, so it is important to provide hints to Webpack's compiler about the purity of the code. The packages.json property will help with these side effects:
{
  "name": "your-project",
  "sideEffects": false
}

The preceding code doesn't contain side effects; therefore, the property should be marked as false to instruct Webpack to remove the unused exports.

In this context, a side effect is defined as a script that performs a special behavior when imported, as opposed to exposing more than one export, and so on. An example would be polyfills, which affect the global project and usually do not provide an export.

  1. In the event of the code having a side effect, an array can be provided as a remedy, such as in the following example:
{
  "name": "your-project",
  "sideEffects": [
    "./src/some-side-effectful-file.js"
  ]
}

The array in this example accepts relative and absolute patterns. 

  1. Note that any imported file is subject to tree shaking. For example, if CSS-loader is used to import a CSS file, it must be added to the side effects list to prevent it from being unintentionally dropped in production mode:
{
  "name": "your-project",
  "sideEffects": [
    "./src/some-side-effectful-file.js",
    "*.css"
  ]
}
  1. Finally, sideEffects can also be set from the module.rules configuration option. So, we've queued up our dead code to be dropped by using the import and export syntax, but we still need to drop it from the bundle. To do that, set the mode configuration option to production. This is done by appending the configuration file, webpack.config.js, as follows:
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  mode: 'development',
  optimization: {
    usedExports: true
  }
  mode: 'production'
};

The --optimize-minimize flag can also be used to enable TerserPlugin. Now that we have understood that, we can run another npm build.

It will now be clear that the whole bundle is minified and mangled. A closer look reveals that the square function is missing; instead, you have a mangled cube function:

function r(e){return e*e*e}n.a=r

With minification and tree shaking, our bundle is now a few bytes smaller! While that may not seem like much in this contrived example, tree shaking can yield a significant decrease in bundle size when working on larger applications with complex dependency trees.

ModuleConcatenationPlugin is needed for the tree shaking to work. It is added by using mode: "production". If you are not using it, remember to add ModuleConcatenationPlugin manually.

The following tasks must be done to take full advantage of tree shaking:

  • Use the ES2015 module syntax (that is, import and export).
  • Ensure no compilers transform your ECMAScript syntax into CommonJS modules.
  • Add a sideEffects property to your package.json file.
  • Use the production configuration option to enable various optimizations, including tree shaking and minification.

When it comes to tree shaking, it often helps to think of your application as a tree. In this analogy, the source code and libraries would be the green leaves and the living part of the tree, respectively. Dead code, however, would represent the dead leaves. Shaking that tree will remove the now defunct code.

This is especially relevant and worth considering when migrating. Given the changes in code deprecation between versions of Webpack, it is important to get your software working at its best before attempting anything like this. This will prevent very difficult bugs from developing.

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

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