Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Reorganize code for maximum tree-shakability #1125

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

steveluscher
Copy link

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:

import { produce } from 'immer';
produce(state, draft => { /* ... */ });

…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():

import { produce } from "immer";

const state = {
  name: { first: "Ada", last: "Byron" },
};

console.log({
  before: state,
  after: produce(state, (draft) => {
    draft.name.last = "Lovelace";
  }),
});

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)

  • 4020 bytes before this PR (link)
  • 3496 bytes gzipped after this PR (link)

Test plan

yarn test

@steveluscher steveluscher force-pushed the tree-shakable-af branch 5 times, most recently from c07b0a2 to c33d4b4 Compare May 18, 2024 23:32
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