zod icon indicating copy to clipboard operation
zod copied to clipboard

perf: mark functions as `@__NO_SIDE_EFFECTS__`

Open serkodev opened this issue 1 month ago • 0 comments

This PR adds @__NO_SIDE_EFFECTS__ notation for all the schema functions: https://github.com/javascript-compiler-hints/compiler-notations-spec/blob/main/no-side-effects-notation-spec.md

This would improve tree-shaking of Zod (mini & core) on users side. For example, the snippet from the docs:

import * as z from 'zod/mini'

const LoginSchema = z.object({
  email: z.email(),
  password: z.string(),
});

Because the object() can not be treated as side-effects free, even LoginSchema is not used, the final bundle still contains an orphan object() call with it's all dependencies.

One solution is to add /* @__PURE__ */ on the user side,

import * as z from 'zod/mini'

const LoginSchema = /* @__PURE__ */ z.object({
  email: z.email(),
  password: z.string(),
});

The downside is this would require the user's manual effort on every schema.

With @__NO_SIDE_EFFECTS__, it will give a hint to the bundler to know object() is side-effects free, and eventually make the whole file shakable (bundle 0KB)

Example of bundling using Rollup: https://stackblitz.com/edit/node-4tux9gdr

This PR made from the https://github.com/open-circle/valibot/pull/995 that @antfu and I co-authored.

Chain calls tree-shaking issue

Since ZodMiniType still includes some chain calls without side effects (such as check, brand, etc.), and because chained calls can't currently be optimized through tree-shake annotations, I'll open another PR to introduce APIs like z.checkFor(z.xxxxx(), ...checks) to address these issues.

serkodev avatar Nov 24 '25 16:11 serkodev