简体   繁体   English

Eslint:手动控制绝对和相对导入

[英]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.我想要一个 eslint 规则,该规则将为从目录内部导入的所有内容提供相对导入路径,为从目录外部导入的所有内容提供绝对路径。

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我的 Component2.tsx 的导入应该是这样的

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".要仅在 Home 目录中强制执行相对导入,您可以配置规则no-restricted-imports以禁止以“Home”开头的导入。

Add this rule to the ESLint configuration file:将此规则添加到 ESLint 配置文件中:

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

This will give an error if the module name to import from starts with "Home".如果要导入的模块名称以“Home”开头,这将产生错误。

In Component2.tsx :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.如果您也想对 Dashboard 目录执行相同的操作,则需要为每个目录使用单独的配置。 You can do this with the overrides key in the ESLint configuration file:您可以使用 ESLint 配置文件中的overrides键来执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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