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: Mark exports as pure, for better tree-shakability #1124

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

Conversation

steveluscher
Copy link

Consider an application that uses only produce but no other methods. This PR allows such an application to be properly tree-shaken by a bundler, to eliminate the other exports altogether.

import { produce } from "immer";
const state = {
  name: "A",
  icon: "III",
  accounts: [
    { address: "X", foo: "bax" },
    { address: "Y", foo: "bax" },
    { address: "Z", foo: "bax" },
  ],
};
const updateAccount = produce(
  (draft: typeof state, newAccount: (typeof state)["accounts"][number]) => {
    const accountIndex = draft.accounts.findIndex(
      ({ address }) => address === newAccount.address
    );
    if (accountIndex !== -1) {
      draft.accounts[accountIndex].address = newAccount.address;
      draft.accounts[accountIndex].foo = newAccount.foo;
    }
  }
);
const nextState = updateAccount(state, { address: "X", foo: "bar" });
console.log(state, nextState);

Bundle

pnpm dlx esbuild --bundle --define:process.env.NODE_ENV='"production"' --tree-shaking  index.ts

Diff as compared to the version on main

658,663d657
<   var produceWithPatches = immer.produceWithPatches.bind(immer);
<   var setAutoFreeze = immer.setAutoFreeze.bind(immer);
<   var setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer);
<   var applyPatches = immer.applyPatches.bind(immer);
<   var createDraft = immer.createDraft.bind(immer);
<   var finishDraft = immer.finishDraft.bind(immer);

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