3

As you may know, in ECMAScript modules exports create a so called live view on a given variable. For example, when we change an exported variable some time later in the code, the change will be visible in modules that import it:

export let x = 1;
x = 2;

-----------

import { x } from "./x.mjs";
console.log(x) // logs 2

But things are a bit different with a default export. A default export is associated with a particular value, not a variable name. So when we do:

let x = 1;
export default x;
x = 2;

---------------------

import x from "./x.mjs";
console.log(x) // logs 1

We get the old value.

How to make default export behave like named export, that is, how to enforce it to be a live view on a given variable?

Playground: glitch.com

marzelin
  • 10,790
  • 2
  • 30
  • 49
  • possible duplicate of [How to initialize a shared javascript module default export](https://stackoverflow.com/q/65541254/1048572) or [Mutable difference between ES6 named and default exports](https://stackoverflow.com/q/58437520/1048572) – Bergi Jan 07 '21 at 11:50

1 Answers1

3

A way to do it:

// x.mjs
let x = 1;
export { x as default }; // this is important to export actual live binding
x = 2;

And then on the other side:

// script.mjs
import test from "./x.mjs";
console.log(test) // will log 2

Another way to do it is with closure, but it will require wrapping of your variable export into a function:

// x.mjs
let x = 1;
export default () => x;
x = 2;
// script.mjs
import { default as _default } from "./x.mjs";
console.log(_default()) // will log 2
Monsieur Merso
  • 1,459
  • 1
  • 15
  • 18