/
no-import-module-exports.js
65 lines (60 loc) · 1.75 KB
/
no-import-module-exports.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
55
56
57
58
59
60
61
62
63
64
65
import minimatch from 'minimatch'
import path from 'path'
import pkgUp from 'pkg-up'
function getEntryPoint(context) {
const pkgPath = pkgUp.sync(context.getFilename())
return require.resolve(path.dirname(pkgPath))
}
module.exports = {
meta: {
docs: {
description: 'Disallow import statements with module.exports',
category: 'Best Practices',
recommended: true,
},
fixable: 'code',
schema: [
{
'type': 'object',
'properties': {
'exceptions': { 'type': 'array' },
},
'additionalProperties': false,
},
],
},
create(context) {
const importDeclarations = []
const entryPoint = getEntryPoint(context)
const options = context.options[0] || {}
let alreadyReported = false
function report(node) {
const fileName = context.getFilename()
const isEntryPoint = entryPoint === fileName
const isIdentifier = node.object.type === 'Identifier'
const hasKeywords = (/^(module|exports)$/).test(node.object.name)
const isException = options.exceptions &&
options.exceptions.some(glob => minimatch(fileName, glob))
if (isIdentifier && hasKeywords && !isEntryPoint && !isException) {
importDeclarations.forEach(importDeclaration => {
context.report({
node: importDeclaration,
message: `Cannot use import declarations in modules that export using ` +
`CommonJS (module.exports = 'foo' or exports.bar = 'hi')`,
})
})
alreadyReported = true
}
}
return {
ImportDeclaration(node) {
importDeclarations.push(node)
},
MemberExpression(node) {
if (!alreadyReported) {
report(node)
}
},
}
},
}