Skip to content

Conversation

@serkodev
Copy link

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 open-circle/valibot#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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant