Tree Shaking

With tree shaking, we can reduce the bundle size by eliminating dead code. Tree shaking is aimed at removing unused code from a JavaScript bundle. Bundlers can automatically detect dead code, to exclude this code from the final bundle.

For example, if two methods are exported from the input.js file, namely validateInput and formatInput, but we're only importing validateInput, the bundler will ensure that the formatInput method won't be included in the final bundle.

// input.js
export function validateInput(input) {
  const isValid = input.length > 10;
  return isValid;
}

export function formatInput(input) {
  const formattedInput = input.toLowerCase();
  return formattedInput;
}
// index.js
import { validateInput } from './input';

const input = document.getElementById("input");
const btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  validateInput(input.value)
})

After tree shaking, the final bundle won't include the formatInput function as it's not referenced in the code.

TreeShaking