Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Last active January 13, 2022 19:13
Show Gist options
  • Save fersilva16/19d1f09cc448858c500d926feda92ea4 to your computer and use it in GitHub Desktop.
Save fersilva16/19d1f09cc448858c500d926feda92ea4 to your computer and use it in GitHub Desktop.
Fix MUI imports from v4
import type { FileInfo, API } from 'jscodeshift';
const newPackagesMap: Record<string, string> = {
'@material-ui/core': '@mui/material',
'@material-ui/icons': '@mui/icons-material',
'@material-ui/styles': '@mui/styles',
};
const newPackages = Object.keys(newPackagesMap);
const getNewPackage = (source: string) => {
const pkg = newPackages.find(key => source.startsWith(key));
return newPackagesMap[pkg!] + source.replace(pkg!, '');
};
export default function transform(file: FileInfo, { jscodeshift }: API) {
const root = jscodeshift(file.source);
const muiImports = root.find(
jscodeshift.ImportDeclaration,
node => !!node.source.value?.toString()?.includes('@material-ui'),
);
muiImports.replaceWith(({ node }) =>
jscodeshift.importDeclaration(
node.specifiers,
jscodeshift.stringLiteral(getNewPackage(node.source.value!.toString())),
node.importKind,
),
);
muiImports
.filter(({ node }) => !!node.specifiers?.some(specifier => specifier.type === 'ImportSpecifier'))
.replaceWith(path => {
let hasDefaultImport = false;
path.node.specifiers!.forEach(specifier => {
if (specifier.type === 'ImportSpecifier') {
path.insertAfter(
jscodeshift.importDeclaration(
[jscodeshift.importDefaultSpecifier(specifier.local || specifier.imported)],
jscodeshift.stringLiteral(
`${path.node.source.value!.toString()}/${specifier.imported?.name || specifier.local?.name}`,
),
path.node.importKind,
),
);
} else {
hasDefaultImport = true;
}
});
if (hasDefaultImport) {
return jscodeshift.importDeclaration(
path.node.specifiers!.filter(specifier => specifier.type === 'ImportDefaultSpecifier'),
path.node.source,
path.node.importKind,
);
}
return undefined;
});
return root.toSource({
quote: 'single',
lineTerminator: '\n',
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment