简体   繁体   中英

Eslint: Manually control absolute and relative imports

I'd like to have a eslint rule which will make to have relative import paths for everything that is imported from inside of the directory and absolute paths for everything that is imported from outside of the directory.

Example: This is my file structure


/Dashboard
    /components
        /Component1.tsx
/Home
    /components
        /Component2.tsx
        /Component3.tsx
    /utils
        /util1.ts
style.ts

I want to have relative imports inside of my Home directory and absolute imports for everything that imported from outside of my Home directory.

My Component2.tsx's imports should look like this

import Component3 from './Component3'
import util1 from './../util1'
import FlexBox from './../../styled'
import Component1 from 'Dashboard/components/component1' // this should be absolute


Could something like this work?

To enforce relative imports only for within the Home directory, you could configure the rule no-restricted-imports to disallow imports starting with "Home".

Add this rule to the ESLint configuration file:

{
  rules: {
    "no-restricted-imports": [
      "error",
      {
        "patterns": ["Home/*"]
      }
    ]
  }
}

This will give an error if the module name to import from starts with "Home".

In Component2.tsx :

import Component3 from 'Home/components/Component3' //error
import util1 from 'Home/utils/util1' //error
import FlexBox from 'Home/abc/xyz/styled' //error
import Component1 from 'Dashboard/components/component1' //no error

If you want to do the same for the Dashboard directory as well, you would need to use a separate configuration for each directory instead. You can do this with the overrides key in the ESLint configuration file:

{
  "overrides": [
    {
      "files": ["Home/*"],
      rules: {
        "no-restricted-imports": [
          "error",
          {
            "patterns": ["Home/*"]
          }
        ]
      }
    },
    {
      "files": ["Dashboard/*"],
      rules: {
        "no-restricted-imports": [
          "error",
          {
            "patterns": ["Dashboard/*"]
          }
        ]
      }
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM