Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/eslint-plugin-import
Path: blob/main/src/rules/no-import-module-exports.js
829 views
1
import minimatch from 'minimatch';
2
import path from 'path';
3
import pkgUp from 'eslint-module-utils/pkgUp';
4
5
function getEntryPoint(context) {
6
const pkgPath = pkgUp({ cwd: context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename() });
7
try {
8
return require.resolve(path.dirname(pkgPath));
9
} catch (error) {
10
// Assume the package has no entrypoint (e.g. CLI packages)
11
// in which case require.resolve would throw.
12
return null;
13
}
14
}
15
16
function findScope(context, identifier) {
17
const { scopeManager } = context.getSourceCode();
18
19
return scopeManager && scopeManager.scopes.slice().reverse().find((scope) => scope.variables.some(variable => variable.identifiers.some((node) => node.name === identifier)));
20
}
21
22
module.exports = {
23
meta: {
24
type: 'problem',
25
docs: {
26
description: 'Disallow import statements with module.exports',
27
category: 'Best Practices',
28
recommended: true,
29
},
30
fixable: 'code',
31
schema: [
32
{
33
'type': 'object',
34
'properties': {
35
'exceptions': { 'type': 'array' },
36
},
37
'additionalProperties': false,
38
},
39
],
40
},
41
create(context) {
42
const importDeclarations = [];
43
const entryPoint = getEntryPoint(context);
44
const options = context.options[0] || {};
45
let alreadyReported = false;
46
47
function report(node) {
48
const fileName = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();
49
const isEntryPoint = entryPoint === fileName;
50
const isIdentifier = node.object.type === 'Identifier';
51
const hasKeywords = (/^(module|exports)$/).test(node.object.name);
52
const objectScope = hasKeywords && findScope(context, node.object.name);
53
const hasCJSExportReference = hasKeywords && (!objectScope || objectScope.type === 'module');
54
const isException = !!options.exceptions && options.exceptions.some(glob => minimatch(fileName, glob));
55
56
if (isIdentifier && hasCJSExportReference && !isEntryPoint && !isException) {
57
importDeclarations.forEach(importDeclaration => {
58
context.report({
59
node: importDeclaration,
60
message: `Cannot use import declarations in modules that export using ` +
61
`CommonJS (module.exports = 'foo' or exports.bar = 'hi')`,
62
});
63
});
64
alreadyReported = true;
65
}
66
}
67
68
return {
69
ImportDeclaration(node) {
70
importDeclarations.push(node);
71
},
72
MemberExpression(node) {
73
if (!alreadyReported) {
74
report(node);
75
}
76
},
77
};
78
},
79
};
80
81