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

2

11

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?

Dulcedulcea answered 6/2, 2020 at 15:38 Comment(3)
There is a rule for that for objects called object-property-newline with the configuration ["error", { "allowAllPropertiesOnSameLine": true }]. However I'm not sure will it work for imports and I was unable to find a rule like that for them.Subkingdom
Thanks @5ar, but that doesn't seem to work :(Dulcedulcea
For the always vertical part you could use npmjs.com/package/eslint-plugin-eslint-vertical-import or github.com/eydrian/tslint-vertical-importEatton
S
15

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!

Subternatural answered 21/12, 2022 at 14:33 Comment(2)
nice one, do you know any similar but for props?Enschede
@FerToasted yes, I know :) See my rule: { rules: { 'object-property-newline': ['error', { allowAllPropertiesOnSameLine: true }] } }Subternatural
D
0

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

Dram answered 13/8 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.