immerjs / immer

Create the next immutable state by mutating the current one
https://immerjs.github.io/immer/
MIT License
27.5k stars 850 forks source link

fix: Mark exports as pure, for better tree-shakability #1124

Open steveluscher opened 3 months ago

steveluscher commented 3 months ago

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);