Prefer Default Export Eslint Error

Prefer Default Export Eslint Error

I am getting this eslint error:

Prefer default export

import React, { Component } from 'react';

class HomePage extends Component {
  render() {
    return (
      <div className="Section">HomePage</div>
    );
  }
}

export { HomePage };

I have tried doing: export { default as Homepage };

and then I get a fatal parsing error.

Then I changed it to:

export default HomePage;

Which clears the eslint error.

But then throws:

'./HomePage' does not contain an export named 'HomePage'.

Because I am calling HomePage like this: import { HomePage } from './HomePage';

If I remove the brackets then I get this error:

"export 'default' (imported as 'HomePage') was not found in './HomePage'

import HomePage from './HomePage';
<PrivateRoute exact path="/" component={HomePage} />

What would be the proper way of changing this to the preferred default export?

1

3 Answers

From eslint-plugin-import

When there is only a single export from a module, prefer using default export over named export.

class HomePage extends Component {
  //....
}

export default HomePage

In another file :

import HomePage from './Hello';

Check here codesandbox

1

Here's an example using functions:

function HomePage() {
    function aHelperMethod() {
        //
    }

    return {
        aHelperMethod,
    }
}

Now to import it in another file

import HomePage from './Hello';

And to use it you'll have to instantiate it

const homePage = HomePage()
homePage.aHelperFunction()

In some cases there should be more than one named export in the module.

export const foo = 'foo';
export const bar = 'bar';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.