Reputation: 40124
I've run into a little hiccup with an export scenario and I am not sure why. I may need a Babel plugin to address it but not sure which.
// a.js
export function fromA() {}
// b.js
export function fromB() {}
// index.js
import * as a from './a'
import * as b from './b'
export default { ...a, ...b}
// test.js
import all from './index'
const { fromA } = all // Works
import { fromA } from './index' // Does not work. Why?
I am running through Babel. Here's my rc:
{
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"transform-export-extensions",
"transform-decorators-legacy"
],
"presets": ["latest", "react"]
}
It seems that I should be able to destucture in test.js within the import statement as usual but no. If, in index.js, I export individual functions then it woks. As in:
import { fromA } from './a'
import { fromB } from './b'
export default { fromA, fromB }
However I'd like to avoid that.
Upvotes: 5
Views: 2312
Reputation: 51490
Though import syntax looks like deconstruction, it's not.
When you're exporting a named variable you can only import it as a named variable. And when you're exporting a default variable, you can only import it as a default one.
For example:
// a.js
export const foo = 1
export const bar = 2
export default { bar: 42, baz: 33 }
import { foo } from './a'
// foo = 1
import { bar } from './a'
// bar = 2
import a from './a'
// a = { bar: 42, baz: 33 }
The only exception is when you're importing a non-es6 module. Since commonjs modules can only export one variable per module, babel falls back to deconstruction importing them.
So, since you're exporting a single object from your index.js
, so you can only import it as the whole object.
Probably what you're looking for is an export * from
statement:
export * from './a'
export * from './b'
It will re-export all named exports from both modules.
Upvotes: 13