Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eslint rule to put a new line inside import

The rule that I'm looking should show error in this case:

import {MY_CONSTANT1, MY_CONSTANT2, MY_CONSTANT3}

And considered as fine in this case:

import {
   MY_CONSTANT1, 
   MY_CONSTANT2, 
   MY_CONSTANT3
}

Is there such eslint rule?

like image 645
Anna Avatar asked Nov 01 '19 08:11

Anna


People also ask

What does 2 mean in ESLint rules?

I defines the severity of a rule. Severity should be one of the following: 0 = off, 1 = warning, 2 = error (you passed "3"). Documentation: https://eslint.org/docs/user-guide/configuring/rules.

How do you set rules in ESLint?

Configuring Rules To change a rule setting, you must set the rule ID equal to one of these values: "off" or 0 - turn the rule off. "warn" or 1 - turn the rule on as a warning (doesn't affect exit code) "error" or 2 - turn the rule on as an error (exit code is 1 when triggered)


3 Answers

I was looking for such a rule for both import and export declaration. As a result I've made a plugin with autofix.

So plugin transforms the code

import { k1, k2 } from 'something'

into

import {
  k1,
  k2
} from 'something'

and code

export { name1, name2, nameN }

into

export {
  name1,
  name2,
  nameN
}
like image 62
Anton Antonov Avatar answered Oct 10 '22 21:10

Anton Antonov


Edit:

Anton Antonov made a plugin that enforces this rule better than object-curly-newline can: https://stackoverflow.com/a/60477269/6179417


Old answer

Add the object-curly-newline rule to your .eslintrc.json, where at least ImportDeclaration is set to always (the other settings have no effect for enforcing newlines in import declarations).

Example:

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

This pattern will now result in an error:

While this is valid:

However, there is a catch - this rule only requires newlines after the opening brace and before the closing brace, so you can still double up on imports as long as they have newlines in between the braces:

like image 21
Fdebijl Avatar answered Oct 10 '22 19:10

Fdebijl


Update on Anton Antonov answer for eslint 8

Because Anton Antonovs repository has been archived and gives meta.fixable error with eslint 8. I Recommend to use ruudandriessen fork of the project .

How to use fork:

  1. Install fork
npm install eslint-plugin-modules-newlines --save-dev
  1. Change all references inside eslint config file of modules-newline -> modules-newlines

Error:

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.
like image 4
Kaspar Avatar answered Oct 10 '22 19:10

Kaspar