Skip to content

feat(eslint-plugin): add a default-off option to autofix remove unused imports #11243

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 103 additions & 1 deletion packages/eslint-plugin/src/rules/no-unused-vars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import {
collectVariables,
createRule,
getFixOrSuggest,
getNameLocationInGlobalDirectiveComment,
isDefinitionFile,
isFunction,
Expand All @@ -23,7 +24,11 @@
} from '../util';
import { referenceContainsTypeQuery } from '../util/referenceContainsTypeQuery';

export type MessageIds = 'unusedVar' | 'usedIgnoredVar' | 'usedOnlyAsType';
export type MessageIds =
| 'unusedVar'
| 'unusedVarSuggestion'
| 'usedIgnoredVar'
| 'usedOnlyAsType';
export type Options = [
| 'all'
| 'local'
Expand All @@ -38,6 +43,9 @@
reportUsedIgnorePattern?: boolean;
vars?: 'all' | 'local';
varsIgnorePattern?: string;
enableAutofixRemoval?: {
imports: boolean;
};
},
];

Expand All @@ -52,6 +60,9 @@
reportUsedIgnorePattern: boolean;
vars: 'all' | 'local';
varsIgnorePattern?: RegExp;
enableAutofixRemoval?: {
imports: boolean;
};
}

type VariableType =
Expand All @@ -74,8 +85,13 @@
extendsBaseRule: true,
recommended: 'recommended',
},
fixable: 'code',
// If generate suggest dynamically, disable the eslint rule.
// eslint-disable-next-line eslint-plugin/require-meta-has-suggestions
hasSuggestions: true,
messages: {
unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}.",
unusedVarSuggestion: 'Remove unused variable.',
usedIgnoredVar:
"'{{varName}}' is marked as ignored but is used{{additional}}.",
usedOnlyAsType:
Expand Down Expand Up @@ -117,6 +133,16 @@
description:
'Regular expressions of destructured array variable names to not check for usage.',
},
enableAutofixRemoval: {
type: 'object',
properties: {
imports: {
type: 'boolean',
description:
'Whether to enable autofix for removing unused imports.',
},
},
},
ignoreClassWithStaticInitBlock: {
type: 'boolean',
description:
Expand Down Expand Up @@ -208,6 +234,10 @@
'u',
);
}

if (firstOption.enableAutofixRemoval) {
options.enableAutofixRemoval = firstOption.enableAutofixRemoval;
}
}

return options;
Expand Down Expand Up @@ -681,12 +711,84 @@
},
};

const fixer: TSESLint.ReportFixFunction = fixer => {
// Find the import statement
const def = unusedVar.defs.find(
d => d.type === DefinitionType.ImportBinding,
);
if (!def) {
return null;
}

const source = context.sourceCode;
const node = def.node;
const decl = node.parent;
if (decl.type !== AST_NODE_TYPES.ImportDeclaration) {
// decl.type is Program, import foo = require('bar');
return fixer.remove(node);
}

const afterNodeToken = source.getTokenAfter(node);
const beforeNodeToken = source.getTokenBefore(node);
const prevBeforeNodeToken = beforeNodeToken
? source.getTokenBefore(beforeNodeToken)
: null;

Check warning on line 735 in packages/eslint-plugin/src/rules/no-unused-vars.ts

View check run for this annotation

Codecov / codecov/patch

packages/eslint-plugin/src/rules/no-unused-vars.ts#L735

Added line #L735 was not covered by tests

// Remove import declaration line if no specifiers are left, import unused from 'a';
if (decl.specifiers.length === 1) {
return fixer.removeRange([decl.range[0], decl.range[1]]);
}

// case: remove braces, import used, { unused } from 'a';
const restNamed = decl.specifiers.filter(
s => s === node && s.type === AST_NODE_TYPES.ImportSpecifier,
);
if (
restNamed.length === 1 &&
afterNodeToken?.value === '}' &&
beforeNodeToken?.value === '{' &&
prevBeforeNodeToken?.value === ','
) {
return fixer.removeRange([
prevBeforeNodeToken.range[0],
afterNodeToken.range[1],
]);
}

// case: Remove comma after node, import { unused, used } from 'a';
if (afterNodeToken?.value === ',') {
return fixer.removeRange([
node.range[0],
afterNodeToken.range[1],
]);
}

// case: Remove comma before node, import { used, unused } from 'a';
if (beforeNodeToken?.value === ',') {
return fixer.removeRange([
beforeNodeToken.range[0],
node.range[1],
]);
}

return null;

Check warning on line 774 in packages/eslint-plugin/src/rules/no-unused-vars.ts

View check run for this annotation

Codecov / codecov/patch

packages/eslint-plugin/src/rules/no-unused-vars.ts#L774

Added line #L774 was not covered by tests
};

context.report({
loc,
messageId,
data: unusedVar.references.some(ref => ref.isWrite())
? getAssignedMessageData(unusedVar)
: getDefinedMessageData(unusedVar),
...getFixOrSuggest({
fixOrSuggest: options.enableAutofixRemoval?.imports
? 'fix'
: 'suggest',
suggestion: {
messageId: 'unusedVarSuggestion',
fix: fixer,
},
}),
});

// If there are no regular declaration, report the first `/*globals*/` comment directive.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,17 @@ function f() {
},
{
code: "import x from 'y';",
errors: [definedError('x')],
errors: [
{
...definedError('x'),
suggestions: [
{
messageId: 'unusedVarSuggestion',
output: '',
},
],
},
],
languageOptions: {
parserOptions: { ecmaVersion: 6, sourceType: 'module' },
},
Expand Down
Loading