On this page

Tree Shaking

Tree shaking, also known as dead code elimination, is a technique to keep JavaScript bundle sizes as small as possible.

Removing such code has several benefits: it shrinks program size, an important consideration in some contexts, and it allows the running program to avoid executing irrelevant operations, which reduces its running time.

How to use Tree Shaking​

Step 1 - Use a bundler that supports tree shaking, such as Webpack, Rollup, or Vite.

Step 2 - Preserve ES Modules (ESM) in the JavaScript sent to your bundler so it can analyze imports and remove unused exports.

How to verify it is working​

We recommend using the source-map-explorer tool to analyze which dependencies end up in your production build. source-map-explorer reviews build output, so it represents the code that will actually be shipped to the browser.

Example​

The Medplum Hello World project uses tree shaking. Build the application with source maps enabled and use a bundle analyzer to inspect which dependencies are included.

OpenOrchid Hello World Tree Shaking

Behind the scenes​

OpenOrchid libraries such as @medplum/core and @medplum/react follow best practices, so tree shaking should work automatically for most build tools.

  • Libraries expose an ESM entry point that lets bundlers analyze named imports
  • Package metadata identifies side effects; @medplum/react preserves CSS imports with "sideEffects": ["*.css"]

Additional reading​