Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/eslint-plugin-import
Path: blob/main/src/rules/no-unassigned-import.js
829 views
1
import path from 'path';
2
import minimatch from 'minimatch';
3
4
import isStaticRequire from '../core/staticRequire';
5
import docsUrl from '../docsUrl';
6
7
function report(context, node) {
8
context.report({
9
node,
10
message: 'Imported module should be assigned',
11
});
12
}
13
14
function testIsAllow(globs, filename, source) {
15
if (!Array.isArray(globs)) {
16
return false; // default doesn't allow any patterns
17
}
18
19
let filePath;
20
21
if (source[0] !== '.' && source[0] !== '/') { // a node module
22
filePath = source;
23
} else {
24
filePath = path.resolve(path.dirname(filename), source); // get source absolute path
25
}
26
27
return globs.find(glob => (
28
minimatch(filePath, glob) ||
29
minimatch(filePath, path.join(process.cwd(), glob))
30
)) !== undefined;
31
}
32
33
function create(context) {
34
const options = context.options[0] || {};
35
const filename = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();
36
const isAllow = source => testIsAllow(options.allow, filename, source);
37
38
return {
39
ImportDeclaration(node) {
40
if (node.specifiers.length === 0 && !isAllow(node.source.value)) {
41
report(context, node);
42
}
43
},
44
ExpressionStatement(node) {
45
if (node.expression.type === 'CallExpression' &&
46
isStaticRequire(node.expression) &&
47
!isAllow(node.expression.arguments[0].value)) {
48
report(context, node.expression);
49
}
50
},
51
};
52
}
53
54
module.exports = {
55
create,
56
meta: {
57
type: 'suggestion',
58
docs: {
59
url: docsUrl('no-unassigned-import'),
60
},
61
schema: [
62
{
63
'type': 'object',
64
'properties': {
65
'devDependencies': { 'type': ['boolean', 'array'] },
66
'optionalDependencies': { 'type': ['boolean', 'array'] },
67
'peerDependencies': { 'type': ['boolean', 'array'] },
68
'allow': {
69
'type': 'array',
70
'items': {
71
'type': 'string',
72
},
73
},
74
},
75
'additionalProperties': false,
76
},
77
],
78
},
79
};
80
81