1 | const {basename, dirname, extname} = require('path');
|
2 |
|
3 | const resolve = require('eslint-module-utils/resolve').default;
|
4 |
|
5 | const {docsUrl} = require('../utilities');
|
6 |
|
7 | function isImageImport(filename) {
|
8 | return /\.(svg|png|jpg)$/.test(filename);
|
9 | }
|
10 |
|
11 | function isImportFromCurrentFolderIndex(contextFilename, resolvedSource) {
|
12 | const isIndex =
|
13 | basename(contextFilename, extname(contextFilename)) === 'index';
|
14 |
|
15 | return isIndex && dirname(resolvedSource) === dirname(contextFilename);
|
16 | }
|
17 |
|
18 | module.exports = {
|
19 | meta: {
|
20 | docs: {
|
21 | description:
|
22 | 'Prefer importing image files from the index file of the directory instead of the direct path to the image file.',
|
23 | category: 'Best Practices',
|
24 | recommended: false,
|
25 | uri: docsUrl('images-no-direct-imports'),
|
26 | },
|
27 | fixable: null,
|
28 | },
|
29 | create(context) {
|
30 | function checkNode(node) {
|
31 | if (
|
32 | !node.source ||
|
33 | !node.source.value ||
|
34 | !isImageImport(node.source.value)
|
35 | ) {
|
36 | return;
|
37 | }
|
38 |
|
39 | const resolvedSource = resolve(node.source.value, context);
|
40 |
|
41 | if (
|
42 | resolvedSource &&
|
43 | !isImportFromCurrentFolderIndex(context.getFilename(), resolvedSource)
|
44 | ) {
|
45 | context.report({
|
46 | node,
|
47 | message: `Prefer importing image files from the index file of the directory ("{{folderPath}}") instead of the direct path to the image file ("{{filePath}}").`,
|
48 | data: {
|
49 | folderPath: dirname(node.source.value),
|
50 | filePath: node.source.value,
|
51 | },
|
52 | });
|
53 | }
|
54 | }
|
55 | return {
|
56 | ImportDeclaration: checkNode,
|
57 | ExportNamedDeclaration: checkNode,
|
58 | ExportAllDeclaration: checkNode,
|
59 | };
|
60 | },
|
61 | };
|