Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order imports with tslint's import-ordering rule

Tags:

import

tslint

On my project tslint's "import-ordering" rule is used

import CopyLensModal from './CopyLensModal'; import FetchStatus from '../../../../../state/generic/models/FetchStatus'; import FlexRow from '../../../../generic/components/FlexRow'; import Geofilter from '../../../../../state/geofilter/models/Geofilter'; import Input from '../../../../generic/components/Input';  import * as React from 'react'; import * as salert from 'sweetalert';  import { func } from '../../../../../types/func'; import { Iterable } from 'immutable'; import { Button } from 'react-bootstrap'; 

tslint is not happy with this order and crashes with error

[2, 1]: Import sources within a group must be alphabetized.
[4, 1]: Import sources within a group must be alphabetized.

This page didn't help that much, I've tried to place imports in many different ways but without luck. Which order will be correct?

like image 379
Denis Avatar asked Jan 23 '17 11:01

Denis


People also ask

Does prettier sort imports?

With the help of prettier and a plugin, we can easily sort imports! As a side note if you're using ESLint I have another article to sort imports using that.

Why do imports sort?

On imports, it groups similar imports together, and makes it easier to see what is being imported from certain packages.


1 Answers

I agree that it's confusing. The problem is that the source string comparisons include the ../.. portions of the module names, so to appease the rule, you would need to sort them like this:

import FetchStatus   from '../../../../../state/generic/models/FetchStatus'; import Geofilter     from '../../../../../state/geofilter/models/Geofilter'; import FlexRow       from '../../../../generic/components/FlexRow'; import Input         from '../../../../generic/components/Input'; import CopyLensModal from './CopyLensModal'; 

The rule has two parts and can be configured to enforce orderings of the import names and sources separately. To enforce only the ordering of names only, you could use a configuration like this:

"ordered-imports": [true, {   "import-sources-order": "any",   "named-imports-order": "case-insensitive" }] 

That would raise an error for imports like this:

import { A, C, B } from 'some-module'; 

but wouldn't enforce ordering for the module paths, etc.

like image 122
cartant Avatar answered Sep 19 '22 17:09

cartant