forked from sindresorhus/eslint-plugin-unicorn
/
import-index.js
64 lines (55 loc) · 1.32 KB
/
import-index.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
'use strict';
const {STATIC_REQUIRE_SELECTOR} = require('./selectors/index.js');
const MESSAGE_ID = 'import-index';
const messages = {
[MESSAGE_ID]: 'Do not reference the index file directly..',
};
const regexp = /^(?<package>@.*?\/.*?|[./]+?.*?)\/(?:\.|(?:index(?:\.js)?))?$/;
const isImportingIndex = value => regexp.test(value);
const normalize = value => value.replace(regexp, '$<package>');
const importIndex = (context, node, argument) => {
if (argument && isImportingIndex(argument.value)) {
return {
node,
messageId: MESSAGE_ID,
fix: fixer => fixer.replaceText(argument, `'${normalize(argument.value)}'`),
};
}
};
const create = context => {
const options = context.options[0] || {};
const rules = {
[STATIC_REQUIRE_SELECTOR]: node => importIndex(context, node, node.arguments[0]),
};
if (!options.ignoreImports) {
rules.ImportDeclaration = node => importIndex(context, node, node.source);
}
return rules;
};
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
ignoreImports: {
type: 'boolean',
default: false,
},
},
},
];
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Enforce importing index files with `.`.',
},
fixable: 'code',
schema,
messages,
},
};