简体   繁体   English

如何配置 ESLint 使其禁止默认导出

[英]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.我已经为此搜索 web 和 StackOverflow 已经有一段时间了,但没有成功。

What I'm trying to do have ESLint mark the following as errors:我正在尝试让 ESLint 将以下内容标记为错误:

export default ...;

with default being the key here. default是这里的关键。 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.到目前为止,我得到的最好的参考是eslint-plugin-import插件及其一些可以让我更接近目标的规则,即no-anonymous-default-export规则。 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?如何配置 ESLint 以使这四个也被视为错误?

You can do this with the no-restricted-syntax rule . 您可以使用no-restricted-syntax规则执行此操作。 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)

如果您已经在使用eslint-plugin-import ,则可以使用no-default-export规则(在2018年2月左右添加)。

As it's already answered in accepted answer, worth mentioning when working in Next.js projects, I like to do:由于它已经在接受的答案中得到了回答,在 Next.js 项目中工作时值得一提,我喜欢这样做:

'import/no-default-export': 'error',
overrides: [
  {
    files: ['src/pages/**/*'],
    rules: {
      'import/no-default-export': 'off',
    },
  },
],

Where the only exception is routed pages, which must be default exported in Next.js.唯一的例外是路由页面,它必须在 Next.js 中默认导出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM