gpt4 book ai didi

javascript - 导入默认导出和命名导出是否会加载模块两次?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:59:51 26 4
gpt4 key购买 nike

当您以下列形式编写导入语句时会发生什么:

import React, { Component } from 'react';

导入模块的解构是否发生在解构一个对象以实现 Component 而不是需要 React.Component?或者它是通过具有完全不同语法的命名导出导入的,尽管它确实类似于解构?

一个重要的推论问题:import React, { Component } ... 是否从 React 模块不必要地加载了 Component 对象两次与简单地 import React ... 相比(假设 Component 是更大的 React 库的组成部分)?

最佳答案

回答你的第一个问题:

不,这不是对象解构。语法可能是以这种方式设置的,但无法确认它们是有意关联的。每the ECMAScript 2015 Language Specification :

Section 15.2.2 Imports

Syntax

[...]

ImportClause :
[...]
ImportedDefaultBinding , NamedImports

[...]

NamedImports :
{ }
{ ImportsList }
{ ImportsList , }

这是完全独立的语法。

回答你的第二个问题:

是的,它导入了两次,一次是 React 用于通过默认导出作为 React.Component 访问,一次是 Component 作为一个命名导出。每the specification :

Section 12.2.2 Static Semantics: BoundNames

[...]

ImportClause : ImportedDefaultBinding , NamedImports

  1. Let names be the BoundNames of ImportedDefaultBinding.

  2. Append to names the elements of the BoundNames of NamedImports.

  3. Return names.

如您所见,您使用 import React, { Component } 导入的名称被绑定(bind)了两次,这意味着您将 React 作为默认导出,因此 React.Component,然后绑定(bind)名称 Component 也附加到您导入的名称。您实际上在两个不同的绑定(bind)或名称下获得了两次。

需要注意的是只有绑定(bind)名称不同。 React.ComponentComponent 引用同一个对象,只是绑定(bind)不同,因为您使用命名导出导入。一旦你导入了 ReactReact.Component 就已经被导入了。 { Component } 所做的只是为已导入的对象创建一个新的绑定(bind)。

关于javascript - 导入默认导出和命名导出是否会加载模块两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824107/

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