|
| 1 | +import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils'; |
| 2 | +import * as util from '../util'; |
| 3 | + |
| 4 | +function isEmptyExport( |
| 5 | + node: TSESTree.Node, |
| 6 | +): node is TSESTree.ExportNamedDeclaration { |
| 7 | + return ( |
| 8 | + node.type === AST_NODE_TYPES.ExportNamedDeclaration && |
| 9 | + node.specifiers.length === 0 && |
| 10 | + !node.declaration |
| 11 | + ); |
| 12 | +} |
| 13 | + |
| 14 | +const exportOrImportNodeTypes = new Set([ |
| 15 | + AST_NODE_TYPES.ExportAllDeclaration, |
| 16 | + AST_NODE_TYPES.ExportDefaultDeclaration, |
| 17 | + AST_NODE_TYPES.ExportNamedDeclaration, |
| 18 | + AST_NODE_TYPES.ExportSpecifier, |
| 19 | + AST_NODE_TYPES.ImportDeclaration, |
| 20 | + AST_NODE_TYPES.TSExportAssignment, |
| 21 | + AST_NODE_TYPES.TSImportEqualsDeclaration, |
| 22 | +]); |
| 23 | + |
| 24 | +export default util.createRule({ |
| 25 | + name: 'no-useless-empty-export', |
| 26 | + meta: { |
| 27 | + docs: { |
| 28 | + description: |
| 29 | + "Disallow empty exports that don't change anything in a module file", |
| 30 | + recommended: false, |
| 31 | + suggestion: true, |
| 32 | + }, |
| 33 | + fixable: 'code', |
| 34 | + hasSuggestions: true, |
| 35 | + messages: { |
| 36 | + uselessExport: 'Empty export does nothing and can be removed.', |
| 37 | + }, |
| 38 | + schema: [], |
| 39 | + type: 'suggestion', |
| 40 | + }, |
| 41 | + defaultOptions: [], |
| 42 | + create(context) { |
| 43 | + function checkNode( |
| 44 | + node: TSESTree.Program | TSESTree.TSModuleDeclaration, |
| 45 | + ): void { |
| 46 | + if (!Array.isArray(node.body)) { |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + let emptyExport: TSESTree.ExportNamedDeclaration | undefined; |
| 51 | + let foundOtherExport = false; |
| 52 | + |
| 53 | + for (const statement of node.body) { |
| 54 | + if (isEmptyExport(statement)) { |
| 55 | + emptyExport = statement; |
| 56 | + |
| 57 | + if (foundOtherExport) { |
| 58 | + break; |
| 59 | + } |
| 60 | + } else if (exportOrImportNodeTypes.has(statement.type)) { |
| 61 | + foundOtherExport = true; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + if (emptyExport && foundOtherExport) { |
| 66 | + context.report({ |
| 67 | + fix: fixer => fixer.remove(emptyExport!), |
| 68 | + messageId: 'uselessExport', |
| 69 | + node: emptyExport, |
| 70 | + }); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return { |
| 75 | + Program: checkNode, |
| 76 | + TSModuleDeclaration: checkNode, |
| 77 | + }; |
| 78 | + }, |
| 79 | +}); |
0 commit comments