繁体   English   中英

ESLint 首选默认导出导入/prefer-default-export

[英]ESLint Prefer default export import/prefer-default-export

嗨,我正在努力理解/让这个 eslint 错误在我的 React 项目中消失。

Prefer default export import/prefer-default-export

Helpers.js 错误指向:

export function getItems() {
  fetch('./data/data_arr.js')
  .then(results => results.json())
  .then(results => this.setState({ items: results }));
}

函数导入:

import { getItems } from '../helpers/helpers';

componentDidMount() {
    getItems.call(this);
}

我试过无济于事:

"rules": {
     "import/prefer-default-export": off,
     ...
}

我需要在函数中添加“默认”吗? export default function getItems() {...}

谢谢

"rules": {
     "import/prefer-default-export": "off",
     ...
}

必须引用off这个词。

要关闭此警告,您可以添加评论

/* eslint-disable import/prefer-default-export */

到您要导出 getItems 的文件的最顶部。

注意,Eslint 只是在这里给你一个样式警告——你的代码没有“错误”,特别是如果你打算将来从同一个文件中导出更多函数。

背景

如果它有用,这里是export defaultexport之间的区别:

使用export default

在这个例子中,文件myFile.js只导出了一点代码; 一个名为myFunction的函数。

// myFile.js

function myFunction() {
    // do something
}

export default myFunction;

当您导入export default ,您可以随意调用它。 所以你可以给它起相同的名字,像这样:

// someOtherFile.js

import myFunction from './myFunction';

// ... now you can use myFunction by calling myFunction()

……或者你可以叫它别的东西

// someOtherFile.js

import someDifferentName from './myFunction';

// ... now you can use myFunction by calling someDifferentName()

当您只从文件中导出一点代码时,通常最好使用export default 每个文件只能有一个默认导出。 有一些关于它有助于摇树的争论,但这并不重要。 实际上,当您将代码导入另一个文件时,这只是一种更好的语法。

单独使用export

如果您想从文件中导出多位代码(或计划在将来export ),您将单独使用export 这有时被称为“命名导出”,因为您在导入时必须使用相同的名称。 例如:

// myFile.js

function myFunction() {
    // do something
}

const someVariable = "Hello World"

export { 
    myFunction, 
    someVariable,
    // plus as many others as you like
    };

现在,当您导入命名导出时,您必须使用相同的名称,并使用解构语法:

// someOtherFile.js

import { myFunction } from './myFunction';

// ... now you can use myFunction by calling myFunction()

您可以导入多个内容:

// someOtherFile.js

import { myFunction, someVariable } from './myFunction';

// ... now you can use myFunction by calling myFunction()
// ... now you can use someVariable as someVariable

有时您可能需要在导入时使用不同的名称。 如果您有两个同名的命名导出(来自两个不同的文件),就会发生这种情况。 在这种情况下,您可以为命名导出使用别名

// someOtherFile.js

import { myFunction as someDifferentName } from './myFunction';

// ... now you can use myFunction by calling someDifferentName()
"rules": {
     "import/prefer-default-export": 0,
     ...
}

使用 0 导入/首选默认导出问题

暂无
暂无

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

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