JavaScript tree shaking

Tree shaking is a term commonly used in the context of JavaScript or dead-code elimination. It relies on the static structure of ES2015 module syntax, that is, import and export. The name and concept have been popularized by the ES2015 module bundler Rollup.

ES2015 is the official version name of the 6th edition of the ECMA-262 standard, in other words ES6

Webpack and Rollup both support tree shaking, though we need to keep certain things in mind so that our code is tree shakeable.

  1. Can be tree shaken as we export as ES modules and only shake is included in the import:
// shakebake.js
const shake = () => console.log('shake')
const bake = () => console.log('bake')

export { shake, bake }
// index.js
import { shake } from './shakebake.js'
  1. Cannot be tree shaken as we have exported an object, and therefore both shake and bake are included in the import:
// shakebake.js
const shake = () => console.log('shake')
const bake = () => console.log('bake')

export default { shake, bake }
// index.js
import { shake } from './shakebake.js'