https://blog.logrocket.com/tree-shaking-and-code-splitting-in-webpack/

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/5ab1a571-c1d6-4991-b8b7-1a4a4f55f4b8/tree-shaking-code-splitting-webpack-1.png

What is tree shaking?

Tree shaking, also known as dead code elimination, is the practice of removing unused code in your production build. It’s important to ship as little code to your end-users as possible. By statically analyzing our source code, we can determine what’s not being used and exclude it from our final bundle.

What is code splitting?

Code splitting, on the other hand, refers to splitting your production build code into multiple modules that are loaded on demand. If you’re utilizing a third-party library in your code after some user interaction, we can exclude that third-party code in our initial bundle and only load it when needed to achieve faster load times.

Tree shaking in webpack

In webpack, tree shaking works with both ECMAScript modules (ESM) and CommonJS, but it does not work with Asynchronous Module Definition (AMD) or Universal Module Definition (UMD).

ESM allows for the most optimal tree shaking because CommonJS, AMD, and UMD can all be non-deterministic and thus, impossible to statically analyze for effective dead code elimination.

In Node.js, for example, you can conditionally run require with a variable to load a random script. Webpack can’t possibly know all of your imports and exports at build time, so it will attempt to tree shake a handful of constructs and bail as soon as things get too dynamic.

This is true for ESM as well, the following code can force webpack to opt out of tree shaking app.js because the use of the import is not static.

import * as App from 'app.js'const variable = // some variable

console.log(App[variable])

And, although UMD is an appealing choice as a module system because it works everywhere, it can’t be tree shaken, so, according to Sean Larkin at Microsoft, it’s best to stick to ESM and let the developers consuming your code handle the conversion from one module system to the other.

Getting started in webpack

When working with webpack, you will realize that some code is more tree-shakable than other similarly functioning code. It’s impossible to cover all the heuristics webpack employs in order to tree shake your code, so we will limit the use cases to a few important ones.

To get a basic webpack project running, install webpack and webpack-cli.

$ yarn init -y
$ yarn add-D webpack webpack-cli

Create two files inside a src directory, src/index.js and src/person.js:

// src/person.jsexport const person = { name: "John", age: 30 };