eslint-plugin-import
eslint-plugin-import copied to clipboard
Auto fix of import without extension
Node.js doesn’t supports imports without file extension:
import client from './client';
This will be error, extension should be provided:
import client from './client.js';
Extensions can be:
jsmjscjs
And need to be resolved, checking what kind of a file exists.
In CommonJS was no such a problem, we can avoid extension:
const client = require(‘./client’);
Because of autoresolver.
So what I want to ask is: Is it possible to autofix cases when extension is missing?
So there was no need to fix such things by hand.
That would be amazing :)!
This isn’t accurate - node native ESM requires extensions, but only for relative imports.
This plugin doesn’t support node native ESM yet, since resolve doesn’t support it yet.
That’s right, I’m talking about relative imports only. What kind of resolve do you mean?
https://npmjs.com/resolve
@ljharb thank you! OK, while this functionality is missing, here is a workaround: no-unresolved from eslint-plugin-putout.
That's a very unsafe autofix to apply automatically; you wouldn't want to use it in babel-transpiled files, and you can't safely apply it to anything in node_modules.
I never use lint for babel-transpiled files and for anything in node_modules, actually. But when I edit file in IDE and forgot to add .js extension, it's very useful to autofix such things on save, and distract me not to manually add an extension :)...
Also this is useful for cases when you migration your codebase to ESM from CommonJS, where using such cases as .. usual practice.
@coderaiser
So what I want to ask is: Is it possible to autofix cases when extension is missing?
eslint-plugin-node/file-extension-in-import is a similar rule that autofixes.
recommend: https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts
@ljharb given there are a few separate eslint plugins available now for this use case, would you be open adding it directly into this eslint plugin as well?
@schickling assuming https://github.com/import-js/eslint-plugin-import/issues/2227#issuecomment-921235109 still applies, the existence of other dangerous implementations isn't an argument for including it.
If it can be done safely, then I would absolutely be interested! Lots of test cases will help inspire confidence, if anyone wants to take it on :-)
I built a tool (ts2esm) which adds explicit file extensions to relative import paths in TypeScript projects. It also adds JSON Import Assertions. The code is open source and tested, so it can serve as inspiration: https://github.com/bennycode/ts2esm
So we already detect these using:
"rules": { "import/extensions": ["error", "ignorePackages"] }
And what this issue asks for is to add an autofix to that rule?