Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
ineedtoknow Avatar asked Jan 11 '21 16:01

ineedtoknow


3 Answers

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"
    }
  }
]
like image 85
Keith Murgic Avatar answered Oct 17 '22 13:10

Keith Murgic


Someone recently created a new ESLint rule specifically for your use case.

It supports fixing the issue for you and the option to allow parent folders.

like image 44
Joel Bourbonnais Avatar answered Oct 17 '22 13:10

Joel Bourbonnais


You can try my new plugin eslint-plugin-absolute-imports-only

...
settings: {
  "absolute-imports-only": {
    project: path.resolve(__dirname, 'tsconfig.json'),
  },
},
like image 2
Thao Tang Avatar answered Oct 17 '22 13:10

Thao Tang