Reputation: 4481
What happens when you write an import statement in the following form:
import React, { Component } from 'react';
Is destructuring of the import module occurring as in destructuring an object to achieve Component
instead of needing React.Component
? Or is it importing with a named export with completely differing syntax, though it does resemble destructuring?
An important corollary question: does import React, { Component } ...
needlessly load up the Component
object from the React
module twice as compared to simply import React ...
(given that Component
is a constituent of the larger React library)?
Upvotes: 3
Views: 217
Reputation: 254926
There is no destructuring happening in the import
syntax. Even though it looks somewhat similar - it's a separated syntax.
The imported identifiers are bindings to the objects created during module initialisation. So practically you get 2 bindings to the same object, which costs you 1 extra reference, nothing more.
No matter how many times in your source code tree you import a module it would only be initialised once, with all the values created just once. And all the import
statements would essentially "bind" to the values in memory without creating duplicates.
Upvotes: 2
Reputation: 57964
To answer your first question:
No, it's not object destructuring. The syntax may have been set up that way to relate but there's no confirmation that they were intentionally made to be related. Per the ECMAScript 2015 Language Specification:
Section 15.2.2 Imports
Syntax
[...]
ImportClause : [...] ImportedDefaultBinding , NamedImports
[...]
NamedImports : { } { ImportsList } { ImportsList , }
It's completely separate syntax.
To answer your second question:
Yes, it imports it twice, once React
for access as React.Component
by the default export, and once as Component
as a named export. Per the specification:
Section 12.2.2 Static Semantics: BoundNames
[...]
ImportClause : ImportedDefaultBinding , NamedImports
Let
names
be the BoundNames ofImportedDefaultBinding
.Append to
names
the elements of the BoundNames ofNamedImports
.Return
names
.
As you can see, the names you import with import React, { Component }
are bound twice, meaning you get React
as the default export and thus React.Component
, and then the bound name Component
is also appended to your imported names. You essentially get it twice under two different bindings or names.
It should be noted that only the bound names are different. React.Component
and Component
refer the same object, just with different bindings because you imported using named exports. Once you import React
, React.Component
has already been imported. All { Component }
does is create a new binding to the already imported object.
Upvotes: 4