eslint-plugin-import icon indicating copy to clipboard operation
eslint-plugin-import copied to clipboard

[import/extensions] Should detect if a relative import is from an ESM before error

Open klarkc opened this issue 4 years ago • 8 comments

According node documentation, in ESM, file extensions are mandatory, with default value for this rule, it breaks Node native behavior.

There is in the same documentation a detailed explanation of how to detect if a module is CJS or ESM.

Originally posted by @klarkc in https://github.com/benmosher/eslint-plugin-import/issues/928#issuecomment-849916859

klarkc avatar May 28 '21 13:05 klarkc

Might be related: #1693 #1003

klarkc avatar May 28 '21 13:05 klarkc

Although it is horrifically unfortunate, this is indeed true in node's default implementation.

If a file being imported relatively is native node ESM, then the extension is mandatory, and this rule's setting should not apply.

ljharb avatar May 31 '21 21:05 ljharb

requiring a extension should always be required now and considered best practices for cross compatibility

jimmywarting avatar Sep 13 '21 14:09 jimmywarting

I don’t agree; the only time node’s native ESM requires extensions is when importing relative files - packages should never force you to include them. Browsers don’t have the concept of extensions, and the best practice remains as it was for decades - webservers should never expose extensions on URLs, except for assets, and the build process handles that for you.

ljharb avatar Sep 13 '21 14:09 ljharb

Just to remember that eslint should DETECT if import is relative AND if it's of an ESM before requiring file extension on the import, that is not true for CJS relative files.

klarkc avatar Sep 13 '21 15:09 klarkc

Another problem is that, with node default behavior (without bundlers, build tools or pre-processors), this rule would break working code, by removing the file extension in a manual or automatic fix (my guess is that node refuses to import relative ESM modules without file extensions).

klarkc avatar Sep 13 '21 15:09 klarkc

@klarkc that would only be the case if this plugin supported native ESM resolution, which it does not (yet), because resolve doesn't yet support it.

ljharb avatar Sep 13 '21 15:09 ljharb

@klarkc that would only be the case if this plugin supported native ESM resolution, which it does not (yet), because resolve doesn't yet support it.

Hello @ljharb, is there anything that could be done to make this work in 2025? Thank you

jirimoravcik avatar May 02 '25 12:05 jirimoravcik