sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.3k stars 365 forks source link

Rule proposal: Require extension for relative imports and re-exports #1194

Open sindresorhus opened 3 years ago

sindresorhus commented 3 years ago

It would enforce using a .js extension for relative imports if it doesn't already have an extension.

We cannot auto-fix as we cannot know whether import foo from './foo'; refers to a file or directory.

This even applies to TypeScript, where you still need the .js extension even if you import other .ts files.

There's already the [import/extensions]() rule, but that project is not very actively maintained, very buggy, and also it doesn't let us use .js extension for TypeScript files. I think it's worth adding this simple rule here.

This rule will not do anything about require() statements.

Fail

import foo from './foo';
export foo from './foo';
await import('./foo');

Pass

import foo from './foo.js';
export foo from './foo.js';
await import('./foo.js');
import foo from './foo.vue';
fisker commented 3 years ago

Fail

import foo from './foo?query=foo.js';

Pass

import foo from './foo.mjs';
import foo from './foo.json' assert { type: "json" };

(This can't test yet, as @babel/eslint-parser missing assertions)

silverwind commented 3 years ago

Fail

import foo from 'module/path/to/file';

Pass

import foo from 'module/path/to/file.js';

import/extensions does already flag this, but I think it does actual resolution. Node docs say "Including the file extension is only necessary for packages without an "exports" field.".

sindresorhus commented 3 years ago

This is now accepted.

jimmywarting commented 3 years ago

I got this error ✖ 2:1 Do not reference the index file directly unicorn/import-index

sindresorhus commented 3 years ago

@jimmywarting Please spend some more effort when interacting on GitHub. Your comment is not relevant to this issue and it's not even clear what you're trying to say.

silverwind commented 3 years ago

An autofix for this rule would also be awesome. import/extensions doesn't provide one, making it very tedious to manually refactor big projects from ./file to ./file.js imports. I guess such a autofix would require file system access to determine the correct extension, thought.

sindresorhus commented 3 years ago

An auto-fix would be quite complex. It's better done in the import plugin as it supports resolvers for TS, etc, even virtual paths.

tjx666 commented 1 year ago

recommend: https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts

roydukkey commented 2 months ago

mysticatea/eslint-plugin-node is another incomplete implementation using it's node/file-extension-in-import rule.