'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 1:[1]
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"
}
}
]
Solution 2:[2]
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.
Solution 3:[3]
You can try my new plugin eslint-plugin-absolute-imports-only
...
settings: {
"absolute-imports-only": {
project: path.resolve(__dirname, 'tsconfig.json'),
},
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GooDeeJAY |
| Solution 2 | Joel Bourbonnais |
| Solution 3 | Thao Tang |
