Tree Shaking

Dead code elimination

Tree Shaking

Tree shaking removes code that is never used from the final bundle. Packem does not expose a top-level treeshake option — tree-shaking is configured through the rollup.treeshake passthrough, which forwards directly to Rollup's treeshake options.

import { defineConfig } from '@visulima/packem/config'

export default defineConfig({
  rollup: {
    treeshake: {
      preset: 'smallest',
      moduleSideEffects: true,
    },
  },
})

There is no defineConfig({ treeshake }) key. Always nest it under rollup.

Defaults

Packem configures Rollup's tree-shaking with these defaults:

{
  // preserve side-effect-only imports
  moduleSideEffects: true,
  // Rollup's most optimal tree-shaking (drops unused getter reads)
  preset: 'smallest',
}

The smallest preset is Rollup's most aggressive setting, while moduleSideEffects: true keeps import './side-effect'-style imports intact so global side effects are not dropped.

Customizing tree-shaking

Because rollup.treeshake is a straight passthrough, any Rollup tree-shake option is available:

export default defineConfig({
  rollup: {
    treeshake: {
      preset: 'recommended',
      propertyReadSideEffects: false,
      unknownGlobalSideEffects: false,
      tryCatchDeoptimization: false,
    },
  },
})

Marking side-effect-free code

To let the bundler drop more code, declare your package side-effect-free in package.json:

{
  "sideEffects": false
}

Combine that with moduleSideEffects to fine-tune which imports are preserved.


  • Minification - Shrink the remaining code
  • Bundler - Tree-shaking applies to the Rollup backend
  • Target - Modern targets enable more aggressive shaking
Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues