javascripttypescripteslinttypescript-eslint

Disallow a folder to import files from another, but still allow other files to import those files


How can eslint be configured to disallow a folder to import files from another folder, but still allow other files in the repo to import those files

I.e. given the following folder structure:

/core/services
/core/models
/core/interfaces

Can I configure a rule to disallow files in /core/services/**/* from being imported by /core/models/**/*, while allowing them to be imported by folders outside of /core/models/**/*?

Imports will use relative paths, so I would want to exclude the relative paths in particular. Absolute paths or root relative paths are an unlikely scenario

Sample import in my project from an interface:

import { Entity } from '../../models/Entity';

Solution

  • This can be accomplished via eslint-plugin-boundaries package

    After installing and enabling the package (see their documentation), configure your .eslintrc.json with:

    {
      "settings": {
        "boundaries/elements": [
            {
                "type": "core models",
                "pattern": "core/models/*"
            },
            {
                "type": "core services",
                "pattern": "core/services/*"
            }
            ...
        ]
    },
    

    And also your rules:

    "rules": {
        "boundaries/element-types": [2, {
            "default": "allow",
            "rules": [
                {
                    "from": "core models",
                    "disallow": ["core interfaces"]
                }
            ]
        }],