|
| 1 | +import { defineRule } from "tsl"; |
| 2 | +import ts from "typescript"; |
| 3 | + |
| 4 | +export const messages = { |
| 5 | + noDuplicateImport: (p: { name: string }) => `Duplicate import of module '${p.name}'.`, |
| 6 | +} as const; |
| 7 | + |
| 8 | +/** |
| 9 | + * Rule to disallow duplicate imports from the same module. |
| 10 | + * |
| 11 | + * @example |
| 12 | + * |
| 13 | + * ```ts |
| 14 | + * // Incorrect |
| 15 | + * import { A } from 'module'; |
| 16 | + * import { B } from 'module'; |
| 17 | + * ``` |
| 18 | + * |
| 19 | + * ```ts |
| 20 | + * // Incorrect |
| 21 | + * import type { A } from 'module'; |
| 22 | + * import type { B } from 'module'; |
| 23 | + * ``` |
| 24 | + * |
| 25 | + * @example |
| 26 | + * |
| 27 | + * ```ts |
| 28 | + * // Correct |
| 29 | + * import { A, B } from 'module'; |
| 30 | + * ``` |
| 31 | + * |
| 32 | + * ```ts |
| 33 | + * // Correct |
| 34 | + * import { A } from 'moduleA'; |
| 35 | + * import type { B } from 'moduleA'; |
| 36 | + * ``` |
| 37 | + */ |
| 38 | +export const noDuplicateImport = defineRule(() => { |
| 39 | + return { |
| 40 | + name: "module/no-duplicate-import", |
| 41 | + createData() { |
| 42 | + return [new Set<string>(), new Set<string>()] as const; |
| 43 | + }, |
| 44 | + visitor: { |
| 45 | + ImportDeclaration(ctx, node) { |
| 46 | + const isTypeOnly = node.importClause?.phaseModifier === ts.SyntaxKind.TypeKeyword; |
| 47 | + const importSource = node.moduleSpecifier.getText(); |
| 48 | + const [vImports, tImports] = ctx.data; |
| 49 | + const importsSet = isTypeOnly ? tImports : vImports; |
| 50 | + if (importsSet.has(importSource)) { |
| 51 | + ctx.report({ |
| 52 | + node: node.moduleSpecifier, |
| 53 | + message: messages.noDuplicateImport({ name: importSource }), |
| 54 | + }); |
| 55 | + return; |
| 56 | + } |
| 57 | + importsSet.add(importSource); |
| 58 | + }, |
| 59 | + }, |
| 60 | + }; |
| 61 | +}); |
0 commit comments