首页 > 解决方案 > 如何使用默认导出保留“实时绑定”

问题描述

您可能知道,在 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

标签: javascriptes6-modules

解决方案


一种方法:

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

推荐阅读