angulareslinteslintrcangular11

ESLint - Only Allow Absolute Import Paths Not Relative


I'm working in an Angular 11 project. A lot of the imports in this project are using a relative path or an absolute path.

I have ESLint set-up for this project, I want to prevent relative import paths, and only allow absolute paths. But I'm not finding a rule to do this.
I've found: no-relative-parent-imports, but it's not giving me issues for paths like: import { HttpService } from "../http/http.service"; or import { RouterService } from "../../services/router/router.service"; (both are not absolute paths, the absolute paths for these would be import { HttpService } from "app/services/http/http.service"; and import { RouterService } from "app/services/router/router.service"; respectively.

I've read this article: https://medium.com/@aayush123/escaping-relative-import-hell-react-native-eslint-atom-57dc2cae5bcc
But I want to avoid adding another thing like Babel if I can avoid it.

Is there a rule for ESLint to prevent any type of relative paths? To only allow absolute paths?


Solution

  • You can add eslint-no-restricted-imports to your .eslintrc file as follows:

    "no-restricted-imports": ["error", {
      "patterns": [".*"]
    }],
    

    If there are some files where you need relative imports, you can add overrides to the eslint-config as follows:

    "overrides": [
      {
        "files": ["*-test.js"],
        "rules": {
          "no-restricted-imports": "off"
        }
      }
    ]