I have the following dir structure
- common
|
|--- Component1
| |
| |--- index.js
| |--- Component1.tsx
| |--- Component1.scss
|
|--- Component2.tsx
|
In Component1's index.js and Compoennt1.tsx I export the default
Component1/index.js
export { default as Component1 } from './Component1'
Component1/Component1.tsx
const Component1 = () => { code... }
export default Component1
and in Component2.tsx I want to import Component1.tsx through default import. However it complains 'no default export in /Component1/index'.
I think the directory /Compoennt1 is exporting Component1.tsx as default, but it's not working
Component2.tsx
// doesn't work
import Component1 from './Component1'
// both works
import { Component1 } from './Component1' or
import Component1 from './Component1/Component1'
Can someone explain why I can't default export/import when it's through a folder or is this how imports/exports work?
CodePudding user response:
Here, it's a named export (named Component1), not a default export:
export { default as Component1 } from './Component1'
which is why importing it via named imports works here:
import { Component1 } from './Component1'
If you want to make it the default export for the Component1/index.js, you need
export { default as default} from './Component1'
Personally, I like to be consistent when writing code - it's nice not to have to try to recall, for every single module, "Did this module export a default or something named?" In a given project, you may find it easier to use default exports everywhere, or named exports everywhere, but not mix them.
