Dethariel
Dethariel

Reputation: 3614

How to configure ESLint so that it disallows default exports

I've been searching the web and StackOverflow for this for quite some time with no success.

What I'm trying to do have ESLint mark the following as errors:

export default ...;

with default being the key here. So far the best I've got is a reference to eslint-plugin-import plugin and some of its rules that can make me closer to the target, namely the no-anonymous-default-export rule. But even with this rule the following default exports would be valid:

const foo = 123
export default foo

export default class MyClass() {}

export default function foo() {}

How can I configure ESLint in such a way that these four would also be considered errors?

Upvotes: 20

Views: 16894

Answers (3)

marko424
marko424

Reputation: 5356

As it's already answered in accepted answer, worth mentioning when working in Next.js projects, I like to do:

'import/no-default-export': 'error',
overrides: [
  // Pages router
  {
    files: ['src/pages/**/*'],
    rules: {
      'import/no-default-export': 'off',
    },
  },
  // App router
  {
    files: ['src/app/**/{page,layout,not-found}.tsx'],
    rules: {
      'import/no-default-export': 'off',
    },
  },
],

Where the only exception is routed pages, which must be default exported in Next.js.

Upvotes: 12

Noel Llevares
Noel Llevares

Reputation: 16037

If you're already using eslint-plugin-import, you can use the no-default-export rule (which was added around February 2018).

Upvotes: 16

btmills
btmills

Reputation: 4542

You can do this with the no-restricted-syntax rule. Try pasting this in the demo to try it out (you'll need to change "Source Type" to "module" first in the options):

/* eslint "no-restricted-syntax": ["error", {
    "selector": "ExportDefaultDeclaration",
    "message": "Prefer named exports"
  }] */
export default class Foo { } // 5:1 - Prefer named exports (no-restricted-syntax)

Upvotes: 23

Related Questions