解构默认导出对象 [英] Destructuring a default export object
问题描述
我可以在导入时构造默认导出对象吗?
Can I destructure a default export object on import?
给定以下导出语法( export default
)
const foo = ...
function bar() { ... }
export default { foo, bar };
以下导入语法是否有效JS?
is the following import syntax valid JS?
import { foo, bar } from './export-file';
我问,因为它在我的系统上工作,但我被告知它不应该按照对规格。
I ask because it DOES work on my system, but I've been told it should NOT work according to the spec.
推荐答案
我可以在导入时构造默认导出对象吗?
Can I destructure a default export object on import?
不。您只能在将对象导入变量后对其进行解构。
No. You can only destructure an object after importing it into a variable.
请注意,导入/导出的语法和语义与对象文字/对象模式的语法和语义完全不同。唯一常见的是,它们都使用花括号,并且它们的简写表示(只有标识符名称和逗号)是无法区分的。
Notice that imports/exports have syntax and semantics that are completely different from those of object literals / object patterns. The only common thing is that both use curly braces, and their shorthand representations (with only identifier names and commas) are indistinguishable.
是以下导入语法有效JS?
Is the following import syntax valid JS?
import { foo, bar } from './export-file';
是的。它确实从模块导入两个命名导出。它是
Yes. It does import two named exports from the module. It's a shorthand notation for
import { foo as foo, bar as bar } from './export-file';
表示声明绑定 foo
和让它引用从 export-file
中以名称 foo
导出的变量,并声明绑定 bar
并让它从 export-file $引用以名称
bar
导出的变量c $ c>。
which means "declare a binding foo
and let it reference the variable that was exported under the name foo
from export-file
, and declare a binding bar
and let it reference the variable that was exported under the name bar
from export-file
".
给定以下导出语法(导出默认值)
Given the following export syntax (export default)
export default { foo, bar };
上面的导入是否与此有关?
does the above import work with this?
否。它的作用是声明一个不可见的变量,用对象 {foo:foo,bar:bar} <初始化它/ code>,并以名称
,这会导致 default
将其导出。
当此模块作为导出文件导入时
,名称默认
将不会被使用,名称 foo
和<$ c $将找不到c> bar SyntaxError
。
No. What it does is to declare an invisible variable, initialise it with the object { foo: foo, bar: bar }
, and export it under the name default
.
When this module is imported as export-file
, the name default
will not be used and the names foo
and bar
will not be found which leads to a SyntaxError
.
要解决此问题,您需要导入默认导出的对象:
To fix this, you either need to import the default-exported object:
import { default as obj } from './export-file';
const {foo: foo, bar: bar} = obj;
// or abbreviated:
import obj from './export-file';
const {foo, bar} = obj;
或者保留导入语法,改为使用命名导出:
Or you keep your import syntax and instead use named exports:
export { foo as foo, bar as bar };
// or abbreviated:
export { foo, bar };
// or right in the respective declarations:
export const foo = …;
export function bar() { ... }
这篇关于解构默认导出对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!