-
Notifications
You must be signed in to change notification settings - Fork 443
/
Copy pathreplaceOrRemoveReactImport.ts
64 lines (57 loc) · 1.14 KB
/
replaceOrRemoveReactImport.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
import { Snippet } from './generateSnippets';
const snippetWithReactImportPrefixes = [
'rfce',
'rfc',
'rfcp',
'rafce',
'rafc',
'rafcp',
'rnfe',
'rnfes',
'rnf',
'rnfs',
'stest',
'sntest',
'srtest',
'snrtest',
'hocredux',
'hoc',
'tsrafc',
'tsrafce',
'tsrcc',
'tsrcredux',
'tsrce',
'tsrpce',
'tsrpc',
'tsrfc',
'tsrfce',
'tsrnf',
'tsrnfs',
];
const replaceOrRemoveReactImport = ({
body,
prefix,
}: {
body: string[];
prefix: Snippet['prefix'];
}) => {
if (!snippetWithReactImportPrefixes.includes(prefix)) {
return body.join('\n');
}
let bodyCopy = [...body];
const reactImportIndex = bodyCopy.findIndex((line) =>
line.match(new RegExp(/import React/, 'g')),
);
if (reactImportIndex !== -1) {
const line = bodyCopy[reactImportIndex];
const newLine = line
.replace(new RegExp(/^import React .*$/, 'g'), '')
.replace(new RegExp(/^import React, /, 'g'), 'import ');
bodyCopy[reactImportIndex] = newLine;
if (!newLine.length) {
bodyCopy = bodyCopy.filter(Boolean);
}
}
return bodyCopy.join('\n');
};
export default replaceOrRemoveReactImport;