Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Last active July 7, 2020 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/33222afa528789d2bb287cc73cee6797 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/33222afa528789d2bb287cc73cee6797 to your computer and use it in GitHub Desktop.
ESLint rule to check for duplicated exported names.
// @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