TTT
TTT

Reputation: 6906

How can I make ESLint enforce imports to either be all on separate lines or all on a single line?

I use ESLint to lint TypeScript. I would like to configure ESLint such that it enforces imports to either be all on separate lines or all on a single line.

Not okay:

import {
    a, b,
    c,
    d
} from "letters";

Okay:

import { a, b, c, d } from "letters";

Okay:

import {
    a,
    b,
    c,
    d
} from "letters";

Is this possible, and if so, how?

Upvotes: 12

Views: 5581

Answers (2)

Holtwick
Holtwick

Reputation: 1966

Add this line in rules to have import properties on one line and export in separate lines:

'object-curly-newline': ['error', {
    ImportDeclaration: 'never',
    ExportDeclaration: 'always'
}],

Exchange never and always as you prefer.

More at https://eslint.org/docs/latest/rules/object-curly-newline#importdeclaration-and-exportdeclaration

Upvotes: 0

Monczek
Monczek

Reputation: 165

I found a solution for this issue!

I spent 4-5 hours yesterday on this topic.

Please use https://github.com/SeinopSys/eslint-plugin-import-newlines (plugin to eslint).

It only takes a few steps to meet your requirements:

  1. Install plugin npm install eslint-plugin-import-newlines --save-dev
  2. Add import-newlines to the plugin section of your .eslintrc configuration file as below.
{
    plugins: ['import-newlines'],
}
  1. Add import-newlines/enforce to the rules section of your .eslintrc configuration file as below (default rule).
{
    rules: {
        'import-newlines/enforce': 'error',
    }
}

or (my rule)

{
    rules: {
        'import-newlines/enforce': ['error', { items: 40, 'max-len': 120 }],
    }
}

My rule works as described below:

  1. For import with length up to 120 characters in one line (counted internally), the import will be forced in one line.
  2. For import with length more than 120 characters in one line (counted internally), the import will be forced on multiple lines (each imported item will be on a separate line)

Good luck and have fun!

Upvotes: 15

Related Questions