forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-imports.js
More file actions
98 lines (79 loc) · 2.83 KB
/
path-imports.js
File metadata and controls
98 lines (79 loc) · 2.83 KB
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
95
96
97
98
import addImports from 'jscodeshift-add-imports';
const barrelImportsToTransform = {
material: {},
'icons-material': {},
};
const muiImportRegExp = /^@mui\/([^/]+)$/;
export default function transformer(fileInfo, api, options) {
const j = api.jscodeshift;
const printOptions = options.printOptions || {
quote: 'single',
trailingComma: true,
};
const root = j(fileInfo.source);
root.find(j.ImportDeclaration).forEach((path) => {
if (!path.node.specifiers.length) {
return;
}
if (path.value.importKind && path.value.importKind !== 'value') {
return;
}
const importPath = path.value.source.value;
const match = importPath.match(muiImportRegExp);
if (!match) {
return;
}
const moduleName = match[1];
const importsToAdd = barrelImportsToTransform[moduleName];
if (!importsToAdd) {
return;
}
const indexesToPrune = [];
path.node.specifiers.forEach((specifier, index) => {
if (specifier.importKind && specifier.importKind !== 'value') {
return;
}
if (specifier.type === 'ImportNamespaceSpecifier') {
return;
}
if (specifier.type === 'ImportSpecifier') {
const name = specifier.imported.name;
if (moduleName === 'material') {
if (name === 'ThemeProvider' || name === 'createTheme') {
importsToAdd.styles ??= [];
importsToAdd.styles.push(specifier);
indexesToPrune.push(index);
return;
}
if (name.endsWith('Classes')) {
const base = name.replace(/Classes$/, '');
const componentName = base.charAt(0).toUpperCase() + base.slice(1); // autocomplete → Autocomplete
importsToAdd[componentName] ??= [];
importsToAdd[componentName].push(
j.importSpecifier(specifier.imported, specifier.local),
);
indexesToPrune.push(index);
return;
}
}
importsToAdd[name] ??= [];
importsToAdd[name].push(j.importDefaultSpecifier(specifier.local));
indexesToPrune.push(index);
}
});
// We prune imports starting with the highest index as otherwise subsequent indexes would become
// invalid once an index that comes before it gets pruned.
indexesToPrune.sort((a, b) => a - b).reverse();
indexesToPrune.forEach((index) => path.get('specifiers', index).prune());
if (!path.node.specifiers.length) {
path.prune();
}
});
Object.entries(barrelImportsToTransform).forEach(([moduleName, importsToAdd]) => {
Object.entries(importsToAdd).forEach(([module, specifiers]) => {
const fullTargetModule = `@mui/${moduleName}/${module}`;
addImports(root, j.importDeclaration(specifiers, j.stringLiteral(fullTargetModule)));
});
});
return root.toSource(printOptions);
}