【问题标题】:Prevent imports outside module except through index防止模块外部导入,除非通过索引
【发布时间】:2021-10-22 15:57:55
【问题描述】:

是否有一个简单的解决方案(也许是 lint 规则?)可以帮助强制通过索引文件导入干净的代码?我想阻止从“表亲”文件中导入代码,除非它是通过索引文件提供的。

例如:

- app
  + dogs
  | + index.ts  
  | + breeds
  | |  + retriever.ts
  | |  + schnauzer.ts
  | + activities
  |    + playing.ts
  |    + walking.ts
  + cats
    + index.ts
    + breeds
    |  + siamese.ts
    |  + persion.ts
    + activities
       + sleeping.ts
       + hunting.ts  

cats/activities/hunting.ts的角度导入:

import { sleeping } from './sleeping'       // VALID - inside same folder
import { siamese } from '../breeds/siamese' // VALID - inside cats module
import { playing } from '../../dogs'        // VALID - importing from an index

import { retriever} from '../../dogs/activities/breeds' // INVALID - cousin file outside module possibly not exported from index

【问题讨论】:

    标签: typescript import


    【解决方案1】:

    您可以使用 eslint 的 import/no-internal-modules rule 并为每个“根”模块配置单独的 .eslintrc 规则。

    在您的 dogs 文件夹中,使用以下内容创建一个新的 .eslintrc 文件:

    {
      "rules": {
        "import/no-internal-modules": [ "error", {
          "allow": [ "app/dogs/**", "app/*" ],
        } ]
      }
    }
    

    这意味着狗文件夹(或狗的任何子文件夹)中的任何 js/ts 文件都可以从其自己的包中导入文件任何包,如 /cats

    对您的 cats 和任何其他“根”模块执行相同操作。

    【讨论】:

      【解决方案2】:

      eslint no-restricted-imports 规则可用于为导入模式提供自定义规则。这种模式可以防止任何 2+ 级上升然后 2+ 级下降,从而防止表亲导入。

      "no-restricted-imports": [
        "warn",
        {
          "patterns": [
            {
              "group": ["**/../../[a-zA-Z]*/[a-zA-Z]*/**"],
              "message": "File not exposed from the module. Consider exporting it from an index"
            }
          ]
        }
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-27
        • 2011-02-24
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多