繁体   English   中英

Eslint 规则在 import 中添加新行

[英]Eslint rule to put a new line inside import

在这种情况下,我正在寻找的规则应该显示错误:

import {MY_CONSTANT1, MY_CONSTANT2, MY_CONSTANT3}

在这种情况下被认为是好的:

import {
   MY_CONSTANT1, 
   MY_CONSTANT2, 
   MY_CONSTANT3
}

有这样的eslint规则吗?

我一直在为进出口报关寻找这样的规则。 结果,我制作了一个带有自动修复的插件

所以插件转换了代码

import { k1, k2 } from 'something'

进入

import {
  k1,
  k2
} from 'something'

和代码

export { name1, name2, nameN }

进入

export {
  name1,
  name2,
  nameN
}

编辑:

Anton Antonov 制作了一个插件,可以比 object-curly-newline 更好地执行此规则: https://stackoverflow.com/a/60477269/6179417


旧答案

object-curly-newline规则添加到您的.eslintrc.json中,其中至少ImportDeclaration设置为 always(其他设置对在导入声明中强制换行无效)。

例子:

"object-curly-newline": ["error", {
   "ObjectExpression": "always",
   "ObjectPattern": { "multiline": true },
   "ImportDeclaration": "always",
   "ExportDeclaration": { "multiline": true, "minProperties": 3 }
}]

此模式现在将导致错误:

虽然这是有效的:

然而,有一个问题——这条规则只需要在左大括号之后和右大括号之前换行,所以只要它们在大括号之间有换行符,你仍然可以加倍导入:

我一直在寻找解决方案,不幸的是只找到了您的问题。 我决定了解一下 eslint 的工作原理以及如何编写自己的插件并创建我的插件。 如果您知道解析的 AST 节点结构,那么使用起来真的很容易。 这是插件的主文件。 Autofix 更棘手,所以我不包括它,因为它偏向于我的格式标准。

module.exports = {
  rules: {
    'single-import-per-line': {
      create (context) {
        return {
          ImportDeclaration(node) {
            if (node.specifiers.length < 2) {
              return;
            }

            let previousImport = node.specifiers[0];
            for (let i = 1; i < node.specifiers.length; i++) {
              const currentImport = node.specifiers[i];

              // Omit the first condition if you want to put default imports on a new line as well
              if (previousImport.type !== 'ImportDefaultSpecifier'
                && currentImport.loc.start.line === previousImport.loc.end.line
              ) {
                context.report({ node, message: 'Your message' });
                return;
              }

              previousImport = currentImport;
            }
          },
        };
      },
    },
  },
};

也许您应该在花括号内使用空格以避免此类错误

import { MY_CONSTANT1, MY_CONSTANT2, MY_CONSTANT2 }

您可以阅读有关对象卷曲间距规则的信息。

更新安东安东诺夫对 eslint 8 的回答

因为 Anton Antonovs 存储库已存档,并且 eslint 8 出现 meta.fixable 错误。我建议使用项目的 ruudandriessen fork

叉子的使用方法:

  1. 安装前叉
npm install eslint-plugin-modules-newlines --save-dev
  1. 更改 modules-newline -> modules-newlines 的 eslint 配置文件中的所有引用

错误:

ESLint: Fixable rules must set the `meta.fixable` property to "code" or "whitespace".
Occurred while linting ... Rule: "modules-newline/import-declaration-newline".
Please see the 'ESLint' output channel for details.

你可以试试这个

"semicolon": [true, "always"]

暂无
暂无

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

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