Skip to content

Commit 100d5ab

Browse files
committed
chore: add tree-shaking skill
1 parent 664b52a commit 100d5ab

1 file changed

Lines changed: 221 additions & 0 deletions

File tree

‎skills/tree-shaking/SKILL.md‎

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
---
2+
name: tree-shaking
3+
description: Practices for writing tree-shakeable JavaScript/TypeScript library code — a consumer must pay only for what they import. Mandatory rules (pure annotations, side-effect-free modules, honest sideEffects, ESM-only) apply to all library code always; architecture tricks (plugin registries, lazy hooks, settings-as-functions, size-limit contracts) apply on user request.
4+
license: MIT
5+
compatibility:
6+
- Claude Code
7+
- Codex
8+
- Cursor
9+
- Gemini CLI
10+
- GitHub Copilot
11+
- Windsurf
12+
- Cline
13+
- Roo Code
14+
- Goose
15+
- Continue
16+
- OpenCode
17+
- Amp
18+
- universal
19+
metadata:
20+
author: dangreen
21+
tags:
22+
- tree-shaking
23+
- bundle-size
24+
- javascript
25+
- typescript
26+
- library
27+
---
28+
29+
# Tree-Shaking
30+
31+
Goal: a consumer pays only for what they import. Everything below serves that.
32+
33+
This skill has two parts:
34+
35+
- **Always** — rules to follow in any library code, without being asked. Violating them silently pins dead code into every consumer bundle.
36+
- **On request** — architecture tricks. Apply them when the user asks to make an API tree-shakeable, reduce bundle size, or design a new library surface.
37+
38+
## Always
39+
40+
### `/* @__NO_SIDE_EFFECTS__ */` on function declarations
41+
42+
Put it on every exported (and shared internal) function that is free of observable side effects. It tells the bundler that any call to this function can be dropped when its result is unused — one annotation covers every call site, including consumer code.
43+
44+
```ts
45+
/* @__NO_SIDE_EFFECTS__ */
46+
export function signal<T>(value?: T): WritableSignal<T | undefined> {
47+
return createSignal(signalOper, { /* ... */ })
48+
}
49+
```
50+
51+
It also belongs on functions that technically **do** mutate something, but whose mutation is pointless if the returned value is thrown away — if dropping the call cannot be observed, mark it:
52+
53+
- registering an entry in a registry that can only ever be looked up via the returned key;
54+
- filling a cache nobody will read (`$source.record ??= new Proxy(...)`);
55+
- attaching lifecycle callbacks to an object nothing else references:
56+
57+
```ts
58+
/* @__NO_SIDE_EFFECTS__ */
59+
export function interval(ms: number): WritableSignal<number> {
60+
const $interval = mountable(signal(0))
61+
onStart($interval, () => {
62+
const timer = setInterval(() => $interval($interval() + 1), ms)
63+
return () => clearInterval(timer)
64+
})
65+
return $interval
66+
}
67+
```
68+
69+
Do **not** mark functions with genuinely observable effects (`effect()`, DOM writes, subscriptions to external state) — the annotation is a claim, and a false claim makes bundlers silently delete live code.
70+
71+
### `/* @__PURE__ */` on module-root calls
72+
73+
Required for **every** function or class call (including `new`) evaluated at module root. Without it a module-level call is treated as a side effect and pins everything it touches into every bundle that imports the module, however little of it is used.
74+
75+
```ts
76+
export const a = /* @__PURE__ */ createElementFactory('a')
77+
export const abbr = /* @__PURE__ */ createElementFactory('abbr')
78+
const reactiveAttributes = /* @__PURE__ */ new Set(['href', 'src'])
79+
const flatHandler = /* @__PURE__ */ createProxyHandler(child => child)
80+
```
81+
82+
Applies to third-party calls too (`/* @__PURE__ */ createContext(...)`). If the callee is already marked `@__NO_SIDE_EFFECTS__`, the call-site annotation is technically redundant — the two are complementary and either one suffices — but annotating the call site anyway is the safe default.
83+
84+
### No side effects at module level
85+
86+
Beyond annotated calls, a module top level must contain only declarations. Concretely:
87+
88+
- No imports-for-effect (`import './setup'`) in shakeable code.
89+
- Module-level mutable state starts as a bare `let x: T | undefined` (free to declare) and is lazily initialized (`x ??= new Set()`) inside the function that needs it — not `const x = new Set()` eagerly.
90+
- Barrel files (`index.ts`) are **pure re-exports only**: no constants, no initialization. Use `export type * from './types.js'` for type-only modules so they are erased at compile time instead of left for the bundler to reason about.
91+
92+
### Honest `sideEffects` in package.json
93+
94+
Every publishable package sets `"sideEffects": false` — **if it is true**. It is a claim, not a decoration:
95+
96+
- If an entry genuinely installs something at import time (e.g. a framework adapter that patches a hook on import), declare `"sideEffects": true` (or list the specific files in an array). Lying lets bundlers drop the whole module.
97+
- CSS or polyfill files that must survive go into the array form: `"sideEffects": ["./dist/index.css"]`.
98+
99+
### ESM-only, statically analyzable output
100+
101+
- `"type": "module"`, `exports` map only; no CJS build, no legacy `main`/`module` fields. Bundlers can only tree-shake statically analyzable ESM.
102+
- Build with a modern target (`esnext`) so no transpile helpers or `Object.defineProperty` shims appear — they defeat static analysis. Beware transpiler class transforms that break `@__PURE__`.
103+
- Publish **unminified** dist (`minify: false`) so the annotations survive into `node_modules`; minification is the consumer's job.
104+
- In a monorepo, externalize workspace dependencies in each package's build config instead of bundling them in — one shakeable module graph, no duplicated copies.
105+
106+
### No TypeScript `enum`
107+
108+
`enum` emits a runtime IIFE object — unshakeable and non-inlinable; `const enum` breaks `isolatedModules`. Use plain `const` numbers/strings (bit flags as `1 << n`), which minify to inlined literals:
109+
110+
```ts
111+
export const NoneFlag = 0
112+
export const MutableFlag = 1 << 0
113+
export const MountableMode = 1 << 3
114+
```
115+
116+
### Named exports, functions over methods
117+
118+
- Export individual named functions, not a default-exported monolith.
119+
- Never make prototype methods the API surface: methods can't be tree-shaken, so a class with `.map()`, `.filter()`, `.subscribe()` ships all of them to every consumer. Expose standalone functions operating on the value instead. Classes are acceptable only where the whole unit is always used together and is off the size-critical path (e.g. an SSR renderer); for variants, prefer injecting a behavior function or `Object.create(base)` forking over subclassing.
120+
121+
## On request
122+
123+
Tricks to apply when the user asks to design a tree-shakeable API, shrink a bundle, or restructure a library.
124+
125+
### Plugin registry instead of a monolithic dispatcher
126+
127+
A `switch` over features references every implementation and is unshakeable. Instead, make every feature an independently importable const whose value is just its id, registered as a side effect of creating that const — implementation reachable only through the import:
128+
129+
```ts
130+
export const effectAttributes = new Map<string, EffectAttributeCallback>()
131+
132+
/* @__NO_SIDE_EFFECTS__ */ // registering an entry nobody can name is unobservable
133+
export function createEffectAttribute(id: string, callback: EffectAttributeCallback) {
134+
effectAttributes.set(id, callback)
135+
return id
136+
}
137+
138+
// feature module — importing `classList$` is what pulls the implementation in
139+
export const classList$ = /* @__PURE__ */ createEffectAttribute('classList$', (element, value) => { /* ... */ })
140+
```
141+
142+
Attach the feature's types via `declare module '...'` augmentation — zero runtime cost. Chart.js's `Chart.register(...)` is the same idea: consumers register only what they use.
143+
144+
### Lazy self-installing hooks
145+
146+
When a core needs an optional subsystem (lifecycle, dev extensions), don't call `install()` unconditionally. Keep `undefined`-initialized module-level hook slots and assign them only from a code path reachable exclusively via the optional public API:
147+
148+
```ts
149+
let lifecycleEdge: ((dep: Node, sub?: Node) => void) | undefined
150+
let lifecycleSettle: (() => void) | undefined
151+
152+
// reachable only via mountable()/onMounted() — apps that never mount drop the whole subsystem
153+
export function touchLifecycle(node: Node): void {
154+
lifecycleEdge = onEdge
155+
lifecycleSettle = settle
156+
settle()
157+
}
158+
```
159+
160+
Hot paths pay only `lifecycleSettle?.()`. If nothing imports the optional API, `onEdge`/`settle` and everything they reference disappear.
161+
162+
### Descriptors that carry their own implementation
163+
164+
Instead of a central runner that switches over descriptor kinds (referencing every handler), return plain objects holding a reference to their own handler — importing `title()` pulls in only `startProperty`:
165+
166+
```ts
167+
/* @__NO_SIDE_EFFECTS__ */
168+
export function title($value: TitleValue): TitlePropertyDescriptor {
169+
return { tag: 'title', value: $value, start: startProperty }
170+
}
171+
```
172+
173+
### Settings as functions instead of an options object
174+
175+
An options object `{ dedupeTime, cacheTime, mapError }` forces one parser that touches every option. Individual closure factories let unused options vanish:
176+
177+
```ts
178+
/* @__NO_SIDE_EFFECTS__ */
179+
export function dedupeTime(time: number): ClientSetting {
180+
return ctx => ctx.dedupeTime = time
181+
}
182+
```
183+
184+
### `bind()` as a factory primitive
185+
186+
`fn.bind(null, arg)` produces a specialized function without a new function body, and combined with `@__NO_SIDE_EFFECTS__` on the factory it is a fully droppable expression:
187+
188+
```ts
189+
/* @__NO_SIDE_EFFECTS__ */
190+
export function createElementFactory<Tag extends ElementName>(tag: Tag) {
191+
return createElement.bind(null, tag) as ElementFactory<Tag>
192+
}
193+
```
194+
195+
### Subpath exports for genuinely separable chunks
196+
197+
When a package has environment-specific or clearly separable parts, give them their own `exports` entries with no shared root so, e.g., server-only code can never be reached from a client import path:
198+
199+
```json
200+
"exports": {
201+
".": "./dist/index.js",
202+
"./vite-plugin": "./dist/vite-plugin.js",
203+
"./renderer": "./dist/renderer.js",
204+
"./client": "./dist/client.js",
205+
"./package.json": "./package.json"
206+
}
207+
```
208+
209+
### Pin tree-shakeability with size-limit
210+
211+
Annotations rot unless tested. Set up size-limit checks by following the `size-limit` skill. The tree-shaking-specific point: measure several **import subsets** of the same dist file (e.g. `{ signal }`, `{ signal, computed, effect }`, `*`), so a shakeability regression shows up as a specific entry blowing its limit rather than a vague total — the delta between subsets is the size of the subsystem being measured as droppable.
212+
213+
For one-off checks of a tricky expression, use locally available tools (rollup/rolldown/terser). Write a tiny entry that imports the module but leaves the result unused, bundle it, and check what survives:
214+
215+
```bash
216+
echo "import { thing } from './dist/index.js'" > /tmp/entry.js
217+
npx rollup /tmp/entry.js --silent --format es # empty output = fully dropped
218+
# or: npx rolldown /tmp/entry.js --silent
219+
# or pipe a single expression through the minifier:
220+
echo "const x = /* @__PURE__ */ create();" | npx terser --module --compress --toplevel
221+
```

0 commit comments

Comments
 (0)