forked from import-js/eslint-plugin-import
/
no-duplicates.js
54 lines (47 loc) · 1.51 KB
/
no-duplicates.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import resolve from 'eslint-module-utils/resolve'
import docsUrl from '../docsUrl'
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 = {
meta: {
docs: {
url: docsUrl('no-duplicates'),
},
},
create: function (context) {
const queryStringOption = context.options[0] && context.options[0]['query-string']
const imported = new Map()
const typesImported = new Map()
const defaultResolver = sourcePath => resolve(sourcePath, context) || sourcePath
const resolver = queryStringOption === 'different' ? (sourcePath => {
const parts = sourcePath.match(/^([^?]*)\?(.*)$/)
if (!parts) {
return defaultResolver(sourcePath)
}
return defaultResolver(parts[1]) + '?' + parts[2]
}) : defaultResolver
return {
'ImportDeclaration': function (n) {
// resolved path will cover aliased duplicates
const resolvedPath = resolver(n.source.value)
const importMap = n.importKind === 'type' ? typesImported : imported
if (importMap.has(resolvedPath)) {
importMap.get(resolvedPath).add(n.source)
} else {
importMap.set(resolvedPath, new Set([n.source]))
}
},
'Program:exit': function () {
checkImports(imported, context)
checkImports(typesImported, context)
},
}
},
}