Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

colinhacks
Copy link
Owner

@colinhacks colinhacks commented May 30, 2025

Closes #4433

I landed some changes that improve the Next.js treeshaking story. I'm pretty astonished at how far Webpack/Next.js is lagging behind Rollup here. Lots of idiosyncrasies.

As always with tree-shaking issues the first thing you should try is a wildcard export:

import * as z from "zod"  // wide support for tree-shaking 
import { z } from "zod"      // not treeshakable by Webpack (Next.js) and esbuild

This is still necessary with both Webpack (at least Next.js) and esbuild. That's pretty disappointing.

Notes on the fixes:

  • Pieces of each locale were getting loaded. Not the whole error map though, just some top-level objects used for word mapping. In fact all top-level objects in the codebase (exported or not) would always get bundled. In the case of locales this was fixed by declaring these as intermediates inside an "error function factory".
  • Various constructed regexes were not marked with @__PURE__.
  • The z.stringbool APIs were bound versions of the Zod Core _stringbool factory, which apparently wasn't shaking. This pulled in the implementations of $ZodUnknown, $ZodBoolean, and $ZodPipe.
  • The fact that $ZodFunction class has methods that return instances of itself threw Webpack for a loop. Dodged this with new inst.constructor().

@colinhacks colinhacks changed the title Fix package.json Improve Next.js tree shaking May 30, 2025
@colinhacks colinhacks merged commit 670a6d2 into main May 30, 2025
4 checks passed
@colinhacks colinhacks deleted the improve-treeshaking-next branch May 30, 2025 07:42
timorthi pushed a commit to timorthi/zod that referenced this pull request Jun 3, 2025
* Fix package.json

* Undo doc changes

* Fix rollup warnings
@colinhacks colinhacks changed the title Improve Next.js tree shaking Improve tree shaking for esbuild/webpack Jun 6, 2025
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.

v4: Next.js treeshaking
1 participant