gpt4 book ai didi

javascript - 导入/导出名称冲突解决

转载 作者:行者123 更新时间:2023-12-05 02:01:25 28 4
gpt4 key购买 nike

在 Node JS 中测试以下模块布局,看起来本地导出的定义总是在名称冲突的情况下替换外部导出的定义(参见 B.js 中的 f1)。

A.js

export const f1 = 'A'

B.js

export * from './A.js'
export const f1 = 'B'

C.js

import * as A from './A.js'
import * as B from './B.js'
console.log(A.f1)
console.log(B.f1)
> node C.js
// A
// B

这是规定吗?我没有在 Ecmascript 规范中找到有关如何管理它的内容。

导入/导出顺序重要吗?

您认为这是扩展模块重载函数和/或添加新函数的可靠方法吗?

最佳答案

Is this a rule? I have not found something about how to manage this in Ecmascript specs.

是的,本地导出优先。事实上,这就是 standardized in the spec :

  1. 对于 module.[[LocalExportEntries]] 中的每个 ExportEntry Record e,执行
    一个。 Assert : 模块 为该导出提供直接绑定(bind)。
    b.将 e.[[ExportName]] 附加到 exportedNames
  2. 对于 module.[[IndirectExportEntries]] 中的每个 ExportEntry Record e,执行
    一个。 Assert : module 为此导出导入一个特定的绑定(bind)。
    b.将 e.[[ExportName]] 附加到 exportedNames

具体来说,您的案例中的 starExport 是以下内容的一部分:

For each ExportEntry Record e in module.[[StarExportEntries]], do
(...)
c. Let starNames be requestedModule.GetExportedNames(exportStarSet).
d. For each element n of starNames, do
i. If SameValue(n, "default") is false, then
1. If n is not an element of exportedNames, then
a. Append n to exportedNames.

那么,回答你的第二个问题:

Do you see this as a reliable method for extending a module overloading functions and/or adding new ones?

是的,它是可靠的,因为它在标准中有规定。

关于javascript - 导入/导出名称冲突解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66533367/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com