Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat(eslint-plugin): [no-unused-vars] 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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
nayounsang wants to merge31 commits intotypescript-eslint:main
base:main
Choose a base branch
Loading
fromnayounsang:auto-unused

Conversation

@nayounsang
Copy link
Contributor

@nayounsangnayounsang commentedMay 23, 2025
edited
Loading

PR Checklist

Overview

Auto fix & suggest unused import statements

  • Test cases that correspond to the issue can be fixed
  • add option:enableAutofixRemoval.imports: boolean , not enable default

examples

importUnused1from'foo';importUnused2,{Used}from'bar';export{Used};import{Used}from'bar';export{Used};// -------------------import{Unused1}from'foo';importUsed1,{Unused2}from'bar';import{Used2,Unused3}from'baz';importUsed3,{Unused4,Used4}from'foobar';export{Used1,Used2,Used3,Used4};importUsed1from'bar';import{Used2}from'baz';importUsed3,{Used4}from'foobar';export{Used1,Used2,Used3,Used4};// -----------------import{/* cmt */Unused1,Used1}from'foo';export{Used1};import{/* cmt */Used1}from'foo';export{Used1};// ------------------importtype{UnusedType}from'foo';import{Used1,Unused1}from'foo';export{Used1};import{Used1}from'foo';export{Used1};// -----------------import{Unused1asu1,Used1asu2}from'foo';export{u2};import{Used1asu2}from'foo';export{u2};

algoORgoal, injae-kim, and Bardiamist reacted with thumbs up emojiinjae-kim reacted with heart emojiinjae-kim reacted with rocket emoji
@typescript-eslint
Copy link
Contributor

Thanks for the PR,@nayounsang!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently onhttps://opencollective.com/typescript-eslint.

@netlify
Copy link

netlifybot commentedMay 23, 2025
edited
Loading

Deploy Preview fortypescript-eslint ready!

NameLink
🔨 Latest commitac3ead7
🔍 Latest deploy loghttps://app.netlify.com/projects/typescript-eslint/deploys/68ac1c15dca7f20008a89768
😎 Deploy Previewhttps://deploy-preview-11243--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 99 (🟢 up 5 from production)
Accessibility: 97 (no change from production)
Best Practices: 100 (no change from production)
SEO: 92 (no change from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to yourNetlify project configuration.

@nayounsangnayounsang marked this pull request as draftMay 23, 2025 15:53
@nx-cloud
Copy link

nx-cloudbot commentedMay 23, 2025
edited
Loading

View yourCI Pipeline Execution ↗ for commitac3ead7

CommandStatusDurationResult
nx test eslint-plugin --coverage=false✅ Succeeded5m 6sView ↗
nx run-many -t lint✅ Succeeded3m 18sView ↗
nx run-many -t typecheck✅ Succeeded2m 12sView ↗
nx test eslint-plugin-internal --coverage=false✅ Succeeded4sView ↗
nx test typescript-estree --coverage=false✅ Succeeded2sView ↗
nx run integration-tests:test✅ Succeeded3sView ↗
nx run types:build✅ Succeeded6sView ↗
nx run generate-configs✅ Succeeded7sView ↗
Additional runs (27)✅ Succeeded...View ↗

☁️Nx Cloud last updated this comment at2025-08-25 08:28:22 UTC

@nayounsang
Copy link
ContributorAuthor

Wow, when adding a new feature, a follow-up development is needed. I'll work on it tomorrow.

@codecov
Copy link

codecovbot commentedMay 24, 2025
edited
Loading

Codecov Report

❌ Patch coverage is96.36364% with4 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.88%. Comparing base (16c344e) to head (ac3ead7).
⚠️ Report is 207 commits behind head on main.

Files with missing linesPatch %Lines
packages/eslint-plugin/src/rules/no-unused-vars.ts96.36%4 Missing⚠️
Additional details and impacted files
@@            Coverage Diff             @@##             main   #11243      +/-   ##==========================================+ Coverage   90.85%   90.88%   +0.03%==========================================  Files         501      505       +4       Lines       50987    51256     +269       Branches     8410     8454      +44     ==========================================+ Hits        46324    46586     +262- Misses       4648     4656       +8+ Partials       15       14       -1
FlagCoverage Δ
unittest90.88% <96.36%> (+0.03%)⬆️

Flags with carried forward coverage won't be shown.Click here to find out more.

Files with missing linesCoverage Δ
packages/eslint-plugin/src/rules/no-unused-vars.ts99.44% <96.36%> (-0.56%)⬇️

... and33 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@nayounsangnayounsang marked this pull request as ready for reviewJune 5, 2025 06:13
Copy link
Member

@kirkwaiblingerkirkwaiblinger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

A great start!

I'm leaving a bit of a drive-by review since I see that there are several major TODOs in the code that need to get resolved. Feel free to reach out if you're looking for help with those! In the meantime, I'm going to leave a Changes Requested review so that this isn't in our ready-to-review queue.

Thanks!


constsource=context.sourceCode;
constnode=def.node;
constdecl=node.parentasTSESTree.ImportDeclaration;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I think that this will be unsound forimport = require-style imports, for example

importx= require('foo')

Let's be sure to include some test coverage with that style ofimport.

Copy link
ContributorAuthor

@nayounsangnayounsangJun 6, 2025
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Oh, nice catch. This isTSImportEqualsDeclaration type.
I test with this code:

{code:`import x = require('foo');import y = require('bar');export { y };      `,errors:[{messageId:'unusedVar'}],options:[{enableAutofixRemoval:{imports:true}}],output:`import y = require('bar');export { y };      `,}

In the existing logic, an error occurs and a more accurate logic is used rather than type casting.
related commit:11ac4fa

data:unusedVar.references.some(ref=>ref.isWrite())
?getAssignedMessageData(unusedVar)
:getDefinedMessageData(unusedVar),
fix:options.enableAutofixRemoval?.imports

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This seems useful as a suggestion, even if the autofix option is disabled. Consider usinggetFixOrSuggest to conditionally provide this fix as a suggestion?

exportfunctiongetFixOrSuggest<MessageIdextendsstring>({
fixOrSuggest,
suggestion,
}:{
fixOrSuggest:'fix'|'none'|'suggest';
suggestion:TSESLint.SuggestionReportDescriptor<MessageId>;
}):
|{fix:TSESLint.ReportFixFunction}
|{suggest:TSESLint.SuggestionReportDescriptor<MessageId>[]}
|undefined{
switch(fixOrSuggest){
case'fix':
return{fix:suggestion.fix};
case'none':
returnundefined;
case'suggest':
return{suggest:[suggestion]};
}
}

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Good idea. However, it would be better to provide suggestions to existing test cases and then resolvethis comment before processing.

if(decl.specifiers.length===1){
returnfixer.removeRange([
decl.range[0],
decl.range[1]+1,// +1 to include "\n"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

to include "\n"

Why do we want to do this exactly? This causes a bug with this technically valid code (please include as a test case - hint, you'll need to usenoFormat):

importxfrom'foo';importyfrom'bar'

My instinct is to say we're better off just leaving a blank line and letting the user decide how to format it afterwards (whether by hand or with prettier or similar).

nayounsang reacted with thumbs up emoji
Copy link
ContributorAuthor

@nayounsangnayounsangJun 6, 2025
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

we're better off just leaving a blank line and letting the user decide how to format it afterwards (whether by hand or with prettier or similar).

Wow, that's right. That should have been it. Plus, it lowers the difficulty of solving the problem and the code becomes simpler.
related commit:9f76441 &633d2c8

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Add new message:unusedVarSuggestion. However, I'm concerned about the proposed message:Remove unused variable.. Any thoughts?

related commit:2c8b740 &9a15d49

@kirkwaiblingerkirkwaiblinger added the awaiting responseIssues waiting for a reply from the OP or another party labelJun 6, 2025
@nayounsang
Copy link
ContributorAuthor

nayounsang commentedJun 11, 2025
edited
Loading

@kirkwaiblinger Hi. I committed my code about your review and TODOs! Please make sure I'm on the right track.
The problem to be solved now is: Problem with unformatted code. (Based on 0-index) Odd specifiers are not deleted.
Um... I run console.log in the local and see results of the ranges need to be deleted, and in this case, the range to delete did not conflict! I don't know why.

// test caseimport{A,B,C,D,E,F,G,Used1,H,I,J,K}from'foo';export{Used1};// expectimport{Used1}from'foo';export{Used1};// receivedimport{B,D,F,Used1,I,K}from'foo'export{Used1};

How can I solve this problem? My idea is to merge the contiguous segments and remove multiple specifiers at once.
For ex

import{A,B,C,D,E,F,G,Used1,H,I,J,K}from'foo';// ->import{Used1,H,I,J,K}from'foo';// ->import{Used1}from'foo';
kirkwaiblinger reacted with eyes emoji

Copy link
ContributorAuthor

@nayounsangnayounsang left a comment
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I'm going to try something different than my previous commit.This is reason & plan:1. Fixing multiple specifers at once is confusing and incompatible with the existing way of reporting.2. Test cases that test for multiple types of imports are more suitable for Unit testing.

Done, I apologize to the reviewer for the change, but I think this is the right direction.

@bradzacherbradzacher changed the titlefeat(eslint-plugin): add a default-off option to autofix remove unused importsfeat(eslint-plugin): [no-unused-vars] add a default-off option to autofix remove unused importsJul 9, 2025
@bradzacherbradzacher removed the awaiting responseIssues waiting for a reply from the OP or another party labelJul 13, 2025
Copy link
Member

@bradzacherbradzacher left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

could you please add a test forimport { Unused1, Unused2 } from 'mod'?
it looks like your logic currently will not remove the import declaration in this case -- which would be the desired result

@bradzacherbradzacher added the awaiting responseIssues waiting for a reply from the OP or another party labelAug 17, 2025
@nayounsang
Copy link
ContributorAuthor

nayounsang commentedAug 17, 2025
edited
Loading

@bradzacher
yes, it is not supported. When handling this, a conflict occurs in the range that the fixer removes, and is therefore ignored.

// receivedimport{a,b}from'foo';// expected// receivedimporta,{b,c}from'foo';console.log(a);// expectedimportafrom'foo';console.log(a)

I'm curious about the direction.
I think this case could be implemented with logic that removes multiple unused specifiers at once, rather than deleting each specifier individually. Is this the right approach?

// To express it in pseudocode...constallNamedSpecifersCount=decl.specifiers.filter(s=>s.type===AST_NODE_TYPES.ImportSpecifier,);if(unusedNamedSpecifiersCount===allNamedSpecifiersCount){returnfixer.removeRange([startBraceToken.range[0],endBraceToken.range[1],]);}
  • That case wasn't found byeslint either. It delete specifiers one by one.
  • I'm not sure if it would be a good idea to have fixer affect other variables that it's not currently handling.

Is there another better way? Anyway I'll try implementing it my way and then req for review.
If you have any comments before then, please let me know! It would be very helpful.

@github-actionsgithub-actionsbot removed the awaiting responseIssues waiting for a reply from the OP or another party labelAug 24, 2025
);
constfirstBraceToken=source.getTokenBefore(
unusedSpecifiers[0],
);
Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This logic assume that unusedVariables collected sequentially from the code.
Deductively, it works fine.
But, I'm not really sure if that's true in all cases.

constanalysisResults=collectVariables(context);constvariables=[        ...Array.from(analysisResults.unusedVariables,variable=>({used:false,          variable,})),        ...Array.from(analysisResults.usedVariables,variable=>({used:true,          variable,})),];

@kirkwaiblingerkirkwaiblinger removed their request for reviewAugust 27, 2025 21:15
Copy link
Member

@JoshuaKGoldbergJoshuaKGoldberg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Looking good! Just a few small touchup suggestions from me, nothing serious.

If@bradzacher and/or@kirkwaiblinger have time to review that'd be great - so I'll hold off on merging for a bit. But if they don't (they're busy this month & we've got a lot of PRs going on) then I feel comfortable merging this soon.

Thanks! 😊

recommended:'recommended',
},
fixable:'code',
// If generate suggest dynamically, disable the eslint rule.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Suggested change
//If generate suggest dynamically, disable the eslint rule.
//Suggestions are generated dynamically by getFixOrSuggest

hasSuggestions:true,
messages:{
unusedVar:"'{{varName}}' is {{action}} but never used{{additional}}.",
unusedVarSuggestion:'Remove unused variable.',

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Bug] This is specific to imports, so we should be more specific here I think.

Suggested change
unusedVarSuggestion:'Remove unusedvariable.',
removeUnusedImport:'Remove unusedimport.',

Comment on lines 674 to +679

/**
* Collect unused import specifiers for the import declaration.
* Access the map by the import declaration.
*/
constunusedImportSpecifiersMap=newWeakMap<

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

[Style] A few interlinked suggestions:

  • This comment doesn't add anything IMO: the variable is already named "unused import specifiers", and its type says that import declarations are the keys
  • TheMap suffix in the name isn't necessary either - it's a map type already
  • It's kind of confusing to read through so much new logic, where a few dozen lines are just to populate a map. Let's move the logic into a function outside of the rule.
Suggested change
/**
*Collectunusedimportspecifiersfortheimportdeclaration.
*Accessthemapbytheimportdeclaration.
*/
constunusedImportSpecifiersMap=newWeakMap<
constunusedImportSpecifiers=
collectUnusedImportSpecifiers(unusedVars);

options:[{enableAutofixRemoval:{imports:true}}],
output:`
`,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Moving#11243 (review) &#11243 (comment) into a thread:

yes, it is not supported. When handling this, a conflict occurs in the range that the fixer removes, and is therefore ignored.

Just to confirm what it looks like the implementation went with: conflicts are ok! ESLint runs up to 10 passes of auto-fixing. If there are 2-3 fixes in a range and only 1-2 get applied in a time, that's fine. It'll get all of them eventually. Fixes are by design meant to always improve codebase quality. They never backtrack.

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Okay. Then, I think I can just delete the complex (conflict-causing) test case and the logic surroundingthis comment (this will greatly simplify the overall logic).
I'll wait for other people's opinions.

@JoshuaKGoldbergJoshuaKGoldberg added the 1 approval>=1 team member has approved this PR; we're now leaving it open for more reviews before we merge labelNov 3, 2025
@nayounsang
Copy link
ContributorAuthor

nayounsang commentedNov 6, 2025
edited
Loading

TODO: This pr adds options separate fromeslint's options, so I think it needs to add something inthe documentation.

@JoshuaKGoldbergJoshuaKGoldberg removed the 1 approval>=1 team member has approved this PR; we're now leaving it open for more reviews before we merge labelNov 7, 2025
@JoshuaKGoldbergJoshuaKGoldberg added the awaiting responseIssues waiting for a reply from the OP or another party labelNov 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@kirkwaiblingerkirkwaiblingerkirkwaiblinger requested changes

@JoshuaKGoldbergJoshuaKGoldbergJoshuaKGoldberg approved these changes

@bradzacherbradzacherAwaiting requested review from bradzacher

Requested changes must be addressed to merge this pull request.

Assignees

No one assigned

Labels

awaiting responseIssues waiting for a reply from the OP or another party

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Enhancement: [no-unused-vars] add a default-off option to autofix remove unused imports

4 participants

@nayounsang@JoshuaKGoldberg@bradzacher@kirkwaiblinger

[8]ページ先頭

©2009-2025 Movatter.jp