Skip to content

Commit

Permalink
[Fix] no-unused-modules: Support destructuring
Browse files Browse the repository at this point in the history
  • Loading branch information
s-h-a-d-o-w committed Feb 28, 2021
1 parent f2db74a commit 04bc1b9
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/rules/no-unused-modules.js
Expand Up @@ -4,7 +4,7 @@
* @author René Fermann
*/

import Exports from '../ExportMap';
import Exports, { recursivePatternCapture } from '../ExportMap';
import { getFileExtensions } from 'eslint-module-utils/ignore';
import resolve from 'eslint-module-utils/resolve';
import docsUrl from '../docsUrl';
Expand Down Expand Up @@ -63,6 +63,8 @@ const IMPORT_DEFAULT_SPECIFIER = 'ImportDefaultSpecifier';
const VARIABLE_DECLARATION = 'VariableDeclaration';
const FUNCTION_DECLARATION = 'FunctionDeclaration';
const CLASS_DECLARATION = 'ClassDeclaration';
const IDENTIFIER = 'Identifier';
const OBJECT_PATTERN = 'ObjectPattern';
const TS_INTERFACE_DECLARATION = 'TSInterfaceDeclaration';
const TS_TYPE_ALIAS_DECLARATION = 'TSTypeAliasDeclaration';
const TS_ENUM_DECLARATION = 'TSEnumDeclaration';
Expand All @@ -80,7 +82,15 @@ function forEachDeclarationIdentifier(declaration, cb) {
cb(declaration.id.name);
} else if (declaration.type === VARIABLE_DECLARATION) {
declaration.declarations.forEach(({ id }) => {
cb(id.name);
if(id.type === OBJECT_PATTERN) {
recursivePatternCapture(id, (pattern) => {
if (pattern.type === IDENTIFIER) {
cb(pattern.name);
}
});
} else {
cb(id.name);
}
});
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/files/no-unused-modules/destructuring-a.js
@@ -0,0 +1 @@
import {a, b} from "./destructuring-b";
2 changes: 2 additions & 0 deletions tests/files/no-unused-modules/destructuring-b.js
@@ -0,0 +1,2 @@
const obj = {a: 1, dummy: {b: 2}};
export const {a, dummy: {b}} = obj;
20 changes: 20 additions & 0 deletions tests/src/rules/no-unused-modules.js
Expand Up @@ -965,3 +965,23 @@ describe('ignore flow types', () => {
invalid: [],
});
});

describe('support (nested) destructuring assignment', () => {
ruleTester.run('no-unused-modules', rule, {
valid: [
test({
options: unusedExportsOptions,
code: 'import {a, b} from "./destructuring-b";',
parser: require.resolve('babel-eslint'),
filename: testFilePath('./no-unused-modules/destructuring-a.js'),
}),
test({
options: unusedExportsOptions,
code: 'const obj = {a: 1, dummy: {b: 2}}; export const {a, dummy: {b}} = obj;',
parser: require.resolve('babel-eslint'),
filename: testFilePath('./no-unused-modules/destructuring-b.js'),
}),
],
invalid: [],
});
});

0 comments on commit 04bc1b9

Please sign in to comment.