javascript - 如何使用默认导出保留“实时绑定”
问题描述
您可能知道,在 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
推荐阅读
- content-management-system - Taxonomy in multilingual environment
- google-chrome - 如何从 Chrome API 获取归档历史记录
- javascript - Edge mediaDevices 无效参数
- c# - 除了使用 ssis 将数据从 sql server 获取到 oracle 之外,还有其他方法吗?
- visual-studio-code - 为什么 VS Code 会破坏我的 Markdown 防护代码块?
- regex - 如何在 jmeter 中创建正则表达式提取器
- linux - 我正在尝试创建一个 payara 集群,但在创建远程节点期间出现错误
- sql - 在单个结果窗口中获取多个函数调用的结果
- swift - 类型“Notification.Name”(又名“NSNotification.Name”)没有成员“UIDevice”
- batch-file - 使用八进制数 08 和 09 以及 SCHTASKS