-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathno-unassigned-import.js
83 lines (74 loc) · 2.06 KB
/
no-unassigned-import.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import path from 'path';
import minimatch from 'minimatch';
import { getPhysicalFilename } from 'eslint-module-utils/contextCompat';
import isStaticRequire from '../core/staticRequire';
import docsUrl from '../docsUrl';
function report(context, node) {
context.report({
node,
message: 'Imported module should be assigned',
});
}
function testIsAllow(globs, filename, source) {
if (!Array.isArray(globs)) {
return false; // default doesn't allow any patterns
}
let filePath;
if (source[0] !== '.' && source[0] !== '/') { // a node module
filePath = source;
} else {
filePath = path.resolve(path.dirname(filename), source); // get source absolute path
}
return globs.find((glob) => minimatch(filePath, glob)
|| minimatch(filePath, path.join(process.cwd(), glob)),
) !== undefined;
}
function create(context) {
const options = context.options[0] || {};
const filename = getPhysicalFilename(context);
const isAllow = (source) => testIsAllow(options.allow, filename, source);
return {
ImportDeclaration(node) {
if (node.specifiers.length === 0 && !isAllow(node.source.value)) {
report(context, node);
}
},
ExpressionStatement(node) {
if (
node.expression.type === 'CallExpression'
&& isStaticRequire(node.expression)
&& !isAllow(node.expression.arguments[0].value)
) {
report(context, node.expression);
}
},
};
}
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
category: 'Style guide',
description: 'Forbid unassigned imports',
url: docsUrl('no-unassigned-import'),
},
schema: [
{
type: 'object',
properties: {
devDependencies: { type: ['boolean', 'array'] },
optionalDependencies: { type: ['boolean', 'array'] },
peerDependencies: { type: ['boolean', 'array'] },
allow: {
type: 'array',
items: {
type: 'string',
},
},
},
additionalProperties: false,
},
],
},
};