esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

Tree-shaking vs. Spread/Object.assign

Open shuckster opened this issue 1 year ago • 0 comments

Source:

// file1.js
export const conf1 = {
  key1: "key1",
  key2: "key2",
};

export const conf2 = {
  key3: "key3",
  key4: "key4",
};

export const full = {
  ...conf1,
  ...conf2,
};

// file2.js
import { conf1 } from './file1.js';
console.log("conf1", conf1);

Output:

(() => {
  // file1.js
  var conf1 = {
    key1: "key1",
    key2: "key2"
  };
  var conf2 = {
    key3: "key3",
    key4: "key4"
  };
  var full = {
    ...conf1,
    ...conf2
  };
  // file2.js
  console.log("conf1", conf1);
})();

Expected:

(() => {
  // file1.js
  var conf1 = {
    key1: "key1",
    key2: "key2"
  };  
  // file2.js
  console.log("conf1", conf1);
})();

The same happens when full is built using Object.assign instead of { ...spread }.

Removing the full object from the source gives the "expected" tree-shaken output.

EDIT - Apologies, my inital post used a "flat" file without exports. I would expect Object.assign to produce the same output in such a file, and for such an output to be correct. My issue is really in the case of a module with exports.

shuckster avatar Feb 28 '25 19:02 shuckster