1

In the first case, I use export and it behaves as I expect

App.js

import * as a from "./a.js";
console.log("a:", a.a); // it would print out "a: a1 "

a.js

let a = "a0";
export { a };
a = "a1";

In the second case, I use export default, and it does not behave as I expect

App.js

import a from "./a.js";
console.log("a:", a); // it would print out "a: a0" ★★★

a.js

let a = "a0";
export default a;
a = "a1";

Why does this happen?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Yao Tao
  • 59
  • 8

1 Answers1

0

I'm not 100% sure about this, but my guess is that the default export gets assigned at export time as a separate variable within the module, whereas the named export is evaluated at import time.

let a = "a0";

// default export assigned to a separate variable. doesn't change if a is reassigned.
const defaultExport = a;

const b = { a };

a = "a1";

// import * as c gets the new value
const c = { a };

// defaultExport hasn't changed
console.log(defaultExport); // a0

// b has the original value
console.log(b); // a0

// c has the new value
console.log(c); // a1
ray
  • 26,557
  • 5
  • 28
  • 27