Kaiser Soze
Kaiser Soze

Reputation: 1498

Nextjs import export modules in one line

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

Upvotes: 0

Views: 4796

Answers (1)

hafiz ali
hafiz ali

Reputation: 1446

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

Upvotes: 2

Related Questions