ES 模块在导出前是否已评估到最后?

Are ES Modules evaluated to their very end before export?

我希望能够导出然后修改一个对象。但是我不确定这是否是意外行为。

test.js:

// Short syntax
export const foo = [];
foo[0] = 1;

// Long syntax
const bar = [];
bar[0] = 1;
export { bar };

index.js:

import { foo, bar } from "./test.js";

console.log("foo:" + foo); // Is it guaranteed to be [1]? Or can it be []?
console.log("bar:" + bar); // I always expect this to be [1].

这可能是一个愚蠢的例子,但有时我有一个对象并想注册一些 methods/properties。我想知道我是否可以导出它然后注册它们。

Are ES modules evaluated to their very end before export?

没有。事实上,导出是在 模块评估之前 声明和注册的。

然而,你实际上想问的是

Are ES modules evaluated to their very end before the modules importing them are evaluated?

是的。 test.js 将在 index.js 被计算 1 之前被完全计算。 importexport 声明在模块中的什么位置并不重要。

1:循环依赖除外。在这种情况下,一个模块可能 运行 在评估所有导入的模块之前,您可能 运行 到 .

Is it guaranteed to be [1]? Or can it be []?

是的,保证是[1](或者const foo还没有初始化的例外)。它永远不会是 []= []foo[0] = 1 总是紧接着彼此执行。