/
typeImportStyle.js
94 lines (87 loc) · 2.31 KB
/
typeImportStyle.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
84
85
86
87
88
89
90
91
92
93
94
const schema = [
{
enum: ['declaration', 'identifier'],
type: 'string',
},
{
additionalProperties: false,
properties: {
ignoreTypeDefault: {
type: 'boolean',
},
},
type: 'object',
},
];
const create = (context) => {
if (context.options[0] === 'declaration') {
return {
ImportDeclaration (node) {
if (node.importKind !== 'type') {
for (const specifier of node.specifiers) {
if (specifier.importKind === 'type') {
context.report({
message: 'Unexpected type import',
node,
});
}
}
}
},
};
} else {
// Default to 'identifier'
const ignoreTypeDefault = context.options[1] &&
context.options[1].ignoreTypeDefault;
let isInsideDeclareModule = false;
return {
DeclareModule () {
isInsideDeclareModule = true;
},
'DeclareModule:exit' () {
isInsideDeclareModule = false;
},
ImportDeclaration (node) {
if (node.importKind !== 'type') {
return;
}
// type specifiers are not allowed inside module declarations:
// https://github.com/facebook/flow/issues/7609
if (isInsideDeclareModule) {
return;
}
if (
ignoreTypeDefault &&
node.specifiers[0] &&
node.specifiers[0].type === 'ImportDefaultSpecifier'
) {
return;
}
context.report({
fix (fixer) {
const imports = node.specifiers.map((specifier) => {
if (specifier.type === 'ImportDefaultSpecifier') {
return 'type default as ' + specifier.local.name;
} else if (specifier.imported.name === specifier.local.name) {
return 'type ' + specifier.local.name;
} else {
return 'type ' + specifier.imported.name + ' as ' + specifier.local.name;
}
});
const source = node.source.value;
return fixer.replaceText(node, 'import {' + imports.join(', ') + '} from \'' + source + '\';');
},
message: 'Unexpected "import type"',
node,
});
},
};
}
};
export default {
create,
meta: {
fixable: 'code',
},
schema,
};