0

I am working on a NextJs app and I have a header folder with a Header.jsx and a default export Header.

In the same folder I have a index.js with this code

export * from './Header'

but if I use it, it fails with an error

Attempted import error: '../components/header' does not contain a default export (imported as 'Header').

If I use this

import Header from './Header'

export default Header

It works fine. is there a way, in NextJs to use the single line export avoiding this repetition?

Thanks

Kaiser Soze
  • 1,362
  • 3
  • 14
  • 31
  • your import and export of header looks in the same code block that confuses me a bit, are you saying that you are exporting from other file or import/export from same file. – hafiz ali Nov 29 '20 at 09:18
  • Does this answer your question? [ES6 exporting/importing in index file](https://stackoverflow.com/questions/34072598/es6-exporting-importing-in-index-file) – hafiz ali Nov 30 '20 at 05:08
  • in next.js components should be exported with export default – Yilmaz Feb 25 '21 at 20:33

1 Answers1

2

export vs default export

  • ES6 provides two ways to export a module from a file: named export and default export.
  1. Named Export: (export)

    • you can have multiple named exports in a file
    // File ./AllComponents.js
    
    export const Comp1= () => {}
    export const Comp2= () => {}
    
    //File ./SomeComponent.js
    // ex. importing a single named export
    import { Comp1 } from "./AllComponents";
    // ex. importing multiple named exports
    import { Comp1, Comp2} from "./AllComponents";
    // ex. giving a named import a different name by using "as":
    import { Comp1 as MyCustomName } from "./AllComponents";
    
  • you can import all of them as one object

    import * as MainComponents from "./AllComponents";
    // use MainComponents.Comp1 and MainComponents.Comp2
    

Default Export: (export default)

  • We can have on ONE default export per file.
  • when importing, we have to do as follows
// File 1: create and export MyComponent
//create a component
const MyComponent = () => {}
//export it
export default MyComponent;

// File 2: import the component in some File
import DefaultExportFromAComponent from "./DefaultExportFromAComponent";
hafiz ali
  • 1,378
  • 1
  • 13
  • 33
  • What I want to do is to use an index file that loads the modules. So Header has its own file, but other components will load it with `./header` since it is exported in the index. So in the index import Header and export it in one single line – Kaiser Soze Nov 29 '20 at 18:35
  • https://stackoverflow.com/questions/34072598/es6-exporting-importing-in-index-file this might answer your question. – hafiz ali Nov 30 '20 at 05:09