Search code examples
javascriptes6-modules

Change ESM export bindings


I'm wondering how the exported bindings of an ES6 module work when destructuring. I'm exporting an object (thing) as a named export -- but also one of its properties (foo), too, which I'm later updating.

This update works when I import the object and reference its prop, but not when I directly import foo, as shown below. I'm guessing the export const... creates a new, immutable binding, but is there any way to retain its reference to the original object upon export?

// module: 'thing.js'

let thing = {
  foo: (x) => console.log(x)
};

const init = () => {
  thing.foo = (x) => console.log("updated");
};

export { init, thing };
export const { foo } = thing;
// index.js

import { foo, thing, init } from "./thing";

init();

foo("test");        // does not work
thing.foo("test");  // update is reflected, here

codesandbox


Solution

  • There is not issue with export/import

    see this example:

    let thing = {
      foo: (x) => console.log(x)
    };
    
    const init = () => {
      thing.foo = (x) => console.log("updated");
    };
    
    const foo = thing.foo;
    
    init();
    foo("test"); //test
    thing.foo("test"); //updated
    

    Variable foo and field thing.foo contains different functions after you rewrite thing.foo inside init function