-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathimport-from-emotion.ts
75 lines (72 loc) · 2.29 KB
/
import-from-emotion.ts
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
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils'
import { createRule } from '../utils'
const messages = {
incorrectImport: `emotion's exports should be imported directly from emotion rather than from react-emotion`
}
export default createRule<never[], keyof typeof messages>({
name: __filename,
meta: {
docs: {
description: 'Ensure styled is imported from @emotion/styled',
recommended: false
},
fixable: 'code',
messages,
schema: [],
type: 'problem'
},
defaultOptions: [],
create(context) {
return {
ImportDeclaration(node) {
if (
node.source.value === 'react-emotion' &&
node.specifiers.some(
x => x.type !== AST_NODE_TYPES.ImportDefaultSpecifier
)
) {
context.report({
node: node.source,
messageId: 'incorrectImport',
fix(fixer) {
if (
node.specifiers[0].type ===
AST_NODE_TYPES.ImportNamespaceSpecifier
) {
return null
}
// default specifiers are always first
if (
node.specifiers[0].type ===
AST_NODE_TYPES.ImportDefaultSpecifier
) {
type ImportSpecifierWithIdentifier =
TSESTree.ImportSpecifier & {
imported: TSESTree.Identifier
}
return fixer.replaceText(
node,
`import ${
node.specifiers[0].local.name
} from '@emotion/styled';\nimport { ${node.specifiers
.filter(
(x): x is ImportSpecifierWithIdentifier =>
x.type === AST_NODE_TYPES.ImportSpecifier &&
x.imported.type === AST_NODE_TYPES.Identifier
)
.map(x =>
x.local.name === x.imported.name
? x.local.name
: `${x.imported.name} as ${x.local.name}`
)
.join(', ')} } from 'emotion';`
)
}
return fixer.replaceText(node.source, "'emotion'")
}
})
}
}
}
}
})