-
Notifications
You must be signed in to change notification settings - Fork 55
/
images-no-direct-imports.js
61 lines (53 loc) · 1.66 KB
/
images-no-direct-imports.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
const {basename, dirname, extname} = require('path');
const resolve = require('eslint-module-utils/resolve').default;
const {docsUrl} = require('../utilities');
function isImageImport(filename) {
return /\.(svg|png|jpg)$/.test(filename);
}
function isImportFromCurrentFolderIndex(contextFilename, resolvedSource) {
const isIndex =
basename(contextFilename, extname(contextFilename)) === 'index';
return isIndex && dirname(resolvedSource) === dirname(contextFilename);
}
module.exports = {
meta: {
docs: {
description:
'Prefer importing image files from the index file of the directory instead of the direct path to the image file.',
category: 'Best Practices',
recommended: false,
uri: docsUrl('images-no-direct-imports'),
},
fixable: null,
},
create(context) {
function checkNode(node) {
if (
!node.source ||
!node.source.value ||
!isImageImport(node.source.value)
) {
return;
}
const resolvedSource = resolve(node.source.value, context);
if (
resolvedSource &&
!isImportFromCurrentFolderIndex(context.getFilename(), resolvedSource)
) {
context.report({
node,
message: `Prefer importing image files from the index file of the directory ("{{folderPath}}") instead of the direct path to the image file ("{{filePath}}").`,
data: {
folderPath: dirname(node.source.value),
filePath: node.source.value,
},
});
}
}
return {
ImportDeclaration: checkNode,
ExportNamedDeclaration: checkNode,
ExportAllDeclaration: checkNode,
};
},
};