|
| 1 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 2 | +module.exports = { |
| 3 | + meta: { |
| 4 | + type: 'suggestion', |
| 5 | + docs: { |
| 6 | + description: |
| 7 | + 'Require top-level React component declarations to be exported', |
| 8 | + }, |
| 9 | + schema: [], |
| 10 | + messages: { |
| 11 | + requireExport: 'Top-level component "{{name}}" must be exported.', |
| 12 | + }, |
| 13 | + }, |
| 14 | + create(context) { |
| 15 | + return { |
| 16 | + Program(node) { |
| 17 | + const exportedNames = collectExportedNames(node); |
| 18 | + |
| 19 | + for (const stmt of node.body) { |
| 20 | + const name = getComponentName(stmt); |
| 21 | + if (name === null) { |
| 22 | + continue; |
| 23 | + } |
| 24 | + |
| 25 | + if (!exportedNames.has(name)) { |
| 26 | + context.report({ |
| 27 | + node: stmt, |
| 28 | + messageId: 'requireExport', |
| 29 | + data: { name }, |
| 30 | + }); |
| 31 | + } |
| 32 | + } |
| 33 | + }, |
| 34 | + }; |
| 35 | + }, |
| 36 | +}; |
| 37 | + |
| 38 | +function isPascalCase(name) { |
| 39 | + return /^[A-Z]/.test(name); |
| 40 | +} |
| 41 | + |
| 42 | +function getComponentName(stmt) { |
| 43 | + if ( |
| 44 | + stmt.type === 'FunctionDeclaration' && |
| 45 | + stmt.id?.name && |
| 46 | + isPascalCase(stmt.id.name) |
| 47 | + ) { |
| 48 | + return stmt.id.name; |
| 49 | + } |
| 50 | + |
| 51 | + if (stmt.type === 'VariableDeclaration' && stmt.declarations.length === 1) { |
| 52 | + const decl = stmt.declarations[0]; |
| 53 | + const name = decl.id?.name; |
| 54 | + if ( |
| 55 | + name && |
| 56 | + isPascalCase(name) && |
| 57 | + decl.init && |
| 58 | + (decl.init.type === 'ArrowFunctionExpression' || |
| 59 | + decl.init.type === 'FunctionExpression') |
| 60 | + ) { |
| 61 | + return name; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return null; |
| 66 | +} |
| 67 | + |
| 68 | +function collectExportedNames(program) { |
| 69 | + const names = new Set(); |
| 70 | + |
| 71 | + for (const stmt of program.body) { |
| 72 | + if (stmt.type === 'ExportNamedDeclaration') { |
| 73 | + if (stmt.declaration) { |
| 74 | + for (const name of getDeclaredNames(stmt.declaration)) { |
| 75 | + names.add(name); |
| 76 | + } |
| 77 | + } |
| 78 | + for (const specifier of stmt.specifiers) { |
| 79 | + names.add(specifier.local.name); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + if (stmt.type === 'ExportDefaultDeclaration') { |
| 84 | + const decl = stmt.declaration; |
| 85 | + if (decl.type === 'Identifier') { |
| 86 | + names.add(decl.name); |
| 87 | + } else if (decl.id) { |
| 88 | + names.add(decl.id.name); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + return names; |
| 94 | +} |
| 95 | + |
| 96 | +function getDeclaredNames(stmt) { |
| 97 | + if (stmt.type === 'VariableDeclaration') { |
| 98 | + return stmt.declarations.map(d => d.id?.name).filter(Boolean); |
| 99 | + } |
| 100 | + return stmt.id?.name ? [stmt.id.name] : []; |
| 101 | +} |
0 commit comments