如何使用默认导出保留 'live binding'

How to retain 'live binding' with default export

如您所知,在 ECMAScript 模块中,导出会在给定变量上创建一个所谓的 实时视图 。例如,当我们稍后在代码中更改导出变量时,更改将在导入它的模块中可见:

export let x = 1;
x = 2;

-----------

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

但是 default 导出有点不同。 default 导出与特定值相关联,而不是变量名。所以当我们这样做时:

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

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

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

我们得到旧值。

如何使 default 导出行为类似于命名导出,即如何强制它成为给定变量的实时视图?

游乐场:glitch.com

一种方法:

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

然后在另一边:

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

另一种方法是使用闭包,但它需要将变量导出包装到函数中:

// 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