Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  57] [ 1]  / answers: 1 / hits: 42246  / 7 Years ago, fri, may 5, 2017, 12:00:00

Can I destructure a default export object on import?



Given the following export syntax (export default)



const foo = ...
function bar() { ... }

export default { foo, bar };


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.


More From » es6-modules

 Answers
20

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.




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';


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?




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() { ... }

[#57876] Thursday, May 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anthonyw

Total Points: 589
Total Questions: 117
Total Answers: 117

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;