Last active
July 7, 2020 07:36
-
-
Save donaldpipowitch/33222afa528789d2bb287cc73cee6797 to your computer and use it in GitHub Desktop.
ESLint rule to check for duplicated exported names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @ts-check | |
/** @type {import("eslint").Rule.RuleModule} */ | |
const rule = { | |
meta: { | |
docs: { | |
description: `You can export a type and a value with the same name in the same file, but that confuses refactoring tools.`, | |
}, | |
}, | |
create(context) { | |
return { | |
Program(node) { | |
// 1) find exported names | |
if (node.type !== 'Program') return; | |
const declarations = []; | |
node.body.forEach((item) => { | |
if (item.type !== 'ExportNamedDeclaration') return; | |
if (!item.declaration) return; | |
// for | |
// - export type Foo = {}; | |
// - export function Foo(){}; | |
if ('id' in item.declaration) { | |
declarations.push(item.declaration); | |
} | |
// for | |
// - export const Foo = {}; | |
if ('declarations' in item.declaration) { | |
item.declaration.declarations.forEach((declaration) => { | |
if (declaration.id.type === 'Identifier') { | |
declarations.push(declaration); | |
} | |
}); | |
} | |
}); | |
// 2) report duplicates | |
declarations.forEach((declaration) => { | |
const foundDuplicate = declarations.some( | |
(checkDeclaration) => | |
checkDeclaration !== declaration && | |
checkDeclaration.id.name === declaration.id.name | |
); | |
if (!foundDuplicate) return; | |
context.report({ | |
node: declaration, | |
message: `There is another export with the name ${declaration.id.name} in this file.`, | |
}); | |
}); | |
}, | |
}; | |
}, | |
}; | |
module.exports = rule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment