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

后端 未结 3 709
情歌与酒
情歌与酒 2021-02-05 00:07

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

import CopyLensModal from \'./CopyLensModal\';
import FetchStatus from \'../../../../../state/generic/mo         


        
相关标签:
3条回答
  • 2021-02-05 01:00

    In file tslint.json add

      "rules": {
        "ordered-imports": [false],
        "object-literal-sort-keys": [false]
      }
    

    For example, then file tslint.json will look like this

    {
      "extends": [
        "tslint:recommended",
        "tslint-react",
        "tslint-config-prettier"
      ],
      "linterOptions": {
        "exclude": [
          "config/**/*.js",
          "node_modules/**/*.ts",
          "coverage/lcov-report/*.js"
        ]
      },
      "rules": {
        "ordered-imports": [false],
        "object-literal-sort-keys": [false]
      }
    }
    
    0 讨论(0)
  • 2021-02-05 01:03

    This error also happens if there is not empty new line added as separation between groups of imports.

    import * as fs from 'fs';
    import * as os from 'os';
    
    import * as bar from './bar';
    import * as foo from './foo';
    

    Also notice if the error says like this:

    ***(5,1): Import sources within a group must be alphabetized.***
    

    This means in the specified file go to line #5 and press enter to add a new empty line there as separator.

    I did that and this resolved my problem. For more reference about this issue review this page

    0 讨论(0)
  • 2021-02-05 01:06

    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.

    0 讨论(0)
提交回复
热议问题