fix: Reorganize code for maximum tree-shakability #1125
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
Because every method is bound up in a
Class
, instantiated in the module factory, then exported, consumers will get every method of Immer in their bundle, whether they use it or not.A slight reorganization of the code would allow their optimizing compilers to tree-shake away the method implementations that they don't need.
Summary
This PR reorganizes the code such that requiring one method of Immer doesn't force you to take a hard dependency on all the others. You can now do this:
…and have all of the other methods that you haven't used (
produceWithPatches
,setAutoFreeze
,setUseStrictShallowCopy
,applyPatches
,createDraft
,finishDraft
) be reaped by your optimizing compiler.Results
Consider this typical application that only uses
produce()
:When bundled with an optimizing compiler:
pnpm dlx esbuild --bundle --define:process.env.NODE_ENV='"production"' --tree-shaking index.ts
This PR (in combination with #1124) results in a bundle that's 13% smaller, gzipped (diff)
Test plan