Skip to content
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

Detect unused JSX component props #848

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/knip/fixtures/react-component/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
59 changes: 59 additions & 0 deletions packages/knip/fixtures/react-component/components.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from "react";
import { ComponentTypeFCProps, ComponentFunctionProps } from "./externalProps";

// Simple component without props, should be ignored
export const MyComponent = () => null;

export interface ComponentInterfaceFCProps {
used: boolean;
unused?: boolean;
}

export const ComponentInterfaceFC: React.FC<ComponentInterfaceFCProps> = (
props: ComponentInterfaceFCProps
) => {
return null;
};

export const ComponentTypeFC: React.FC<ComponentTypeFCProps> = (
props: ComponentTypeFCProps
) => {
return null;
};

export function ComponentFunction(props: ComponentFunctionProps) {
// Usages inside the component should not count
if (props.used || props.unused) {
return null;
}
return null;
}

interface ComponentFunctionDestructuredProps {
used: boolean;
unused?: boolean;
}

export function ComponentFunctionDestructured({
used,
unused,
}: ComponentFunctionDestructuredProps) {
// Usages inside the component should not count
if (used || unused) {
return null;
}
return null;
}

interface ComponentClassProps {
used: boolean;
unused?: boolean;
}

export class ComponentClass extends React.Component<ComponentClassProps> {
render() {
return null;
}
}


9 changes: 9 additions & 0 deletions packages/knip/fixtures/react-component/externalProps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export type ComponentTypeFCProps = {
used: boolean;
unused?: boolean;
};

export interface ComponentFunctionProps {
used: boolean;
unused?: boolean;
}
22 changes: 22 additions & 0 deletions packages/knip/fixtures/react-component/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import * as React from "react";
import {
MyComponent,
ComponentInterfaceFC,
ComponentTypeFC,
ComponentFunction,
ComponentFunctionDestructured,
ComponentClass,
} from "./components";

export const App = () => {
return (
<React.Fragment>
<MyComponent />
<ComponentInterfaceFC used={true} />
<ComponentTypeFC used={true} />
<ComponentFunction used={true} />
<ComponentFunctionDestructured used={true} />
<ComponentClass used={true} />
</React.Fragment>
);
};
21 changes: 21 additions & 0 deletions packages/knip/fixtures/react-component/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "@fixtures/class-members",
"dependencies": {
"react": "^18.3.1"
},
"knip": {
"entry": [
"index.tsx"
],
"project": [
"*.ts",
"*.tsx"
],
"include": [
"classMembers"
]
},
"devDependencies": {
"@types/react": "^18.3.12"
}
}
7 changes: 1 addition & 6 deletions packages/knip/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,7 @@
"postcreate-plugin": "biome format --write schema.json schema-jsonc.json src/ConfigurationValidator.ts",
"generate-plugin-defs": "node ./scripts/generate-plugin-defs.js && biome check --write src/plugins/index.ts src/types/PluginNames.ts src/schema/plugins.ts"
},
"files": [
"dist",
"vendor",
"schema.json",
"schema-jsonc.json"
],
"files": ["dist", "vendor", "schema.json", "schema-jsonc.json"],
"dependencies": {
"@nodelib/fs.walk": "1.2.8",
"@snyk/github-codeowners": "1.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/knip/src/IssueCollector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ const isMatch = timerify(picomatch.isMatch, 'isMatch');
* - Hands them out, to be consumed by reporters
*/
export class IssueCollector {
private cwd: string;
private rules: Rules;
private filters: Filters;
private issues = initIssues();
Expand All @@ -36,6 +35,7 @@ export class IssueCollector {
private tagHints = new Set<TagHint>();
private ignorePatterns = new Set<string>();
private isMatch: (filePath: string) => boolean;
public cwd: string;

constructor({ cwd, rules, filters }: IssueCollectorOptions) {
this.cwd = cwd;
Expand Down
2 changes: 2 additions & 0 deletions packages/knip/src/IssueFixer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class IssueFixer {
isFixDependencies = true;
isFixUnusedTypes = true;
isFixUnusedExports = true;
isFixUnusedComponentProps = true;

unusedTypeNodes: Map<string, Set<Fix>> = new Map();
unusedExportNodes: Map<string, Set<Fix>> = new Map();
Expand All @@ -30,6 +31,7 @@ export class IssueFixer {
this.isFixDependencies = fixTypes.length === 0 || fixTypes.includes('dependencies');
this.isFixUnusedTypes = fixTypes.length === 0 || fixTypes.includes('types');
this.isFixUnusedExports = fixTypes.length === 0 || fixTypes.includes('exports');
this.isFixUnusedComponentProps = fixTypes.length === 0 || fixTypes.includes('react-component');
}

public addUnusedTypeNode(filePath: string, fixes: Fixes | undefined) {
Expand Down
47 changes: 26 additions & 21 deletions packages/knip/src/ProjectPrincipal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,14 @@ export class ProjectPrincipal {
languageServiceHost: ts.LanguageServiceHost;
};

findReferences?: ts.LanguageService['findReferences'];
_findReferences?: ts.LanguageService['findReferences'];
get findReferences() {
if (!this._findReferences) {
const languageService = ts.createLanguageService(this.backend.languageServiceHost, ts.createDocumentRegistry());
this._findReferences = timerify(languageService.findReferences);
}
return this._findReferences;
}

constructor({
compilerOptions,
Expand Down Expand Up @@ -246,10 +253,15 @@ export class ProjectPrincipal {

const resolve = (specifier: string) => this.backend.resolveModuleNames([specifier], sourceFile.fileName)[0];

const { imports, exports, scripts, traceRefs } = _getImportsAndExports(sourceFile, resolve, typeChecker, {
...options,
skipExports,
});
const { imports, exports, scripts, traceRefs, jsxComponents } = _getImportsAndExports(
sourceFile,
resolve,
typeChecker,
{
...options,
skipExports,
}
);

const { internal, resolved, specifiers, unresolved, external } = imports;

Expand Down Expand Up @@ -299,6 +311,7 @@ export class ProjectPrincipal {
unresolved: unresolvedImports,
external,
},
jsxComponents,
exports,
scripts,
traceRefs,
Expand All @@ -310,28 +323,20 @@ export class ProjectPrincipal {
this.backend.fileManager.sourceFileCache.delete(filePath);
}

public findUnusedMembers(filePath: string, members: ExportMember[]) {
if (!this.findReferences) {
const languageService = ts.createLanguageService(this.backend.languageServiceHost, ts.createDocumentRegistry());
this.findReferences = timerify(languageService.findReferences);
}

return members.filter(member => {
if (member.jsDocTags.has(PUBLIC_TAG)) return false;
const referencedSymbols = this.findReferences?.(filePath, member.pos) ?? [];
public findRefsForMembers(filePath: string, members: ExportMember[]) {
const refsForMembers = [];
for (const member of members) {
if (member.jsDocTags.has(PUBLIC_TAG)) continue;
const referencedSymbols = this.findReferences(filePath, member.pos) ?? [];
const refs = referencedSymbols.flatMap(refs => refs.references).filter(ref => !ref.isDefinition);
return refs.length === 0;
});
refsForMembers.push({ member, refs });
}
return refsForMembers;
}

public hasExternalReferences(filePath: string, exportedItem: Export) {
if (exportedItem.jsDocTags.has(PUBLIC_TAG)) return false;

if (!this.findReferences) {
const languageService = ts.createLanguageService(this.backend.languageServiceHost, ts.createDocumentRegistry());
this.findReferences = timerify(languageService.findReferences);
}

const referencedSymbols = this.findReferences(filePath, exportedItem.pos);

if (!referencedSymbols?.length) return false;
Expand Down
2 changes: 2 additions & 0 deletions packages/knip/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export const ISSUE_TYPES: IssueType[] = [
'enumMembers',
'classMembers',
'duplicates',
'componentProps',
];

export const ISSUE_TYPE_TITLE: Record<IssueType, string> = {
Expand All @@ -204,6 +205,7 @@ export const ISSUE_TYPE_TITLE: Record<IssueType, string> = {
enumMembers: 'Unused exported enum members',
classMembers: 'Unused exported class members',
duplicates: 'Duplicate exports',
componentProps: 'Unused JSX component props',
};

export const FIX_FLAGS = {
Expand Down
Loading