Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check duplicates for normal imports and flow type imports separately #334

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions src/rules/no-duplicates.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,35 @@ import Set from 'es6-set'

import resolve from '../core/resolve'

function checkImports(imported, context) {
for (let [module, nodes] of imported.entries()) {
if (nodes.size > 1) {
for (let node of nodes) {
context.report(node, `'${module}' imported multiple times.`)
}
}
}
}

module.exports = function (context) {
const imported = new Map()
const typesImported = new Map()
return {
'ImportDeclaration': function (n) {
// resolved path will cover aliased duplicates
let resolvedPath = resolve(n.source.value, context) || n.source.value
const resolvedPath = resolve(n.source.value, context) || n.source.value
const importMap = n.importKind === 'type' ? typesImported : imported

if (imported.has(resolvedPath)) {
imported.get(resolvedPath).add(n.source)
if (importMap.has(resolvedPath)) {
importMap.get(resolvedPath).add(n.source)
} else {
imported.set(resolvedPath, new Set([n.source]))
importMap.set(resolvedPath, new Set([n.source]))
}
},

'Program:exit': function () {
for (let [module, nodes] of imported.entries()) {
if (nodes.size > 1) {
for (let node of nodes) {
context.report(node, `'${module}' imported multiple times.`)
}
}
}
checkImports(imported, context)
checkImports(typesImported, context)
},
}
}
12 changes: 12 additions & 0 deletions tests/src/rules/no-duplicates.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ ruleTester.run('no-duplicates', rule, {
// #86: every unresolved module should not show up as 'null' and duplicate
test({ code: 'import foo from "234artaf";' +
'import { shoop } from "234q25ad"' }),

// #225: ignore duplicate if is a flow type import
test({
code: "import { x } from './foo'; import type { y } from './foo'",
parser: 'babel-eslint',
}),
],
invalid: [
test({
Expand Down Expand Up @@ -45,5 +51,11 @@ ruleTester.run('no-duplicates', rule, {
"'non-existent' imported multiple times.",
],
}),

test({
code: "import type { x } from './foo'; import type { y } from './foo'",
parser: 'babel-eslint',
errors: ['\'./foo\' imported multiple times.', '\'./foo\' imported multiple times.'],
}),
],
})