Eslint-plugin-import: Rule proposal: no-relative-path

Created on 16 Nov 2016  路  5Comments  路  Source: benmosher/eslint-plugin-import

In larger projects I've noticed an increasing trend in using packages like module-alias to avoid using relative paths all together.

I work mostly in React based projects and it's very common to reuse components all over your application, making deeply nested relative paths a common problem.
But once an alias is used I've noticed that it's easy to forget using them because writing import './Something' is faster than the full aliased path.

That's why I think adding a rule that disable relative paths all together would be useful for projects that have aliasing in place.

I want to open a discussion about it first, and if you guys are busy with other stuff I'd be happy to submit a PR on it if you think this rule would make sense.

Most helpful comment

@stipsan I found out you can do this with the core rule(s) no-restricted-imports/no-restricted-modules!

Example config:

no-restricted-imports:
    - error
    - patterns: [../*]

Kudos to @ljharb. https://github.com/benmosher/eslint-plugin-import/issues/834#issuecomment-301944276

All 5 comments

In projects with aliasing, you usually _want_ relative paths within component directories, so that if you move a folder containing a subtree of your app, you only have to update the path of the entry point everywhere.

If you're using aliasing everywhere, I don't see the benefit of aliasing at all over ../.

Two benefits I can think of:

  • Explicit dependencies instead of implicit (you don't need to know what folder the file you're looking at is in order to know where its imports are coming from).
  • Easy search and replace changed paths, or find out where a module is being used by just searching for the full path.

I also would find this feature useful, in our project we resolve every import agains our src folder, and find it really useful when refactoring and changing component folders later in the project.

You just need to add this to your webpack.config.js

resolve: {
  modules: ['src', 'node_modules'],
}

I would love this feature.

I think this feature would be very helpful as well. One option it should have is to differentiate between ./ and ../. I think it's still good to be able to include things at the same level (or lower) without writing the whole alias path (such as component directories), but better to use aliases for things which are in a higher directory.

@stipsan I found out you can do this with the core rule(s) no-restricted-imports/no-restricted-modules!

Example config:

no-restricted-imports:
    - error
    - patterns: [../*]

Kudos to @ljharb. https://github.com/benmosher/eslint-plugin-import/issues/834#issuecomment-301944276

Was this page helpful?
0 / 5 - 0 ratings