eslint-plugin-better-tree-shaking

ESLint plugin to improve tree-shaking of library code

Improve tree-shaking of your app or library by detecting top-level side-effects that bundlers can't eliminate. The plugin suggests annotating them with /* @__PURE__ */ comments.

Examples

Top-level side effects prevent bundlers from tree-shaking unused exports. Here are common patterns and their fixes:

import FOO from './foo'

// Calling a function
export const t1_wrong = FOO()                        // ❌
export const t1_correct = /* @__PURE__ */ FOO()      // ✅

// Calling a method
export const t2_wrong = FOO.bar()                    // ❌
export const t2_correct = /* @__PURE__ */ FOO.bar()  // ✅

// Accessing nested members
export const t3_wrong = FOO.bar.bazz                           // ❌
export const t3_correct = /* @__PURE__ */ (() => FOO.bar.bazz)() // ✅

// Multiple side effects in object
export const t4_wrong = {
  a: FOO(),
  [FOO.bar.bazz]: FOO.bar(),
} // ❌

export const t4_correct = /* @__PURE__ */ (() => ({
  a: FOO(),
  [FOO.bar.bazz]: FOO.bar(),
}))() // ✅

Setup with ESLint

Install the eslint-plugin-better-tree-shaking package.

Add better-tree-shaking to the plugins section of your ESLint configuration file and Add thebetter-tree-shaking/no-top-level-side-effects rule to the rules section.

{
  "plugins": ["better-tree-shaking"],
  "rules": {
    "better-tree-shaking/no-top-level-side-effects": "error"
  }
}