在第一种情况下,我使用export
,它的行为正如我所期望的
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";
在第二种情况下,我使用export default
,它的行为不像我期望的那样
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";
为什么会发生这种情况?
我不是100%确定这一点,但我的猜测是默认的export在导出时作为模块内的一个单独变量被分配,而命名的export在导入时被评估。
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